Default value for C# properties/functions?


  • In VB .NET, I can create a property or function that doesn't explicitly return a value. For example:

      ReadOnly Property FallThrough() As Integer

        End Get
      End Property

    I can leave that property as-is, and it will return 0 when I retrieve its value. I'd like to be able to do the same thing in C#, but it looks like it requires a value to be explicitly returned. The problem is I'm going to have properties with many different data types (so I can't just return 0 in every case) and my requirements say that I can't use the System.Reflection namespace.

    Basically, I have some code that goes into each property, if certain criteria aren't met, I'd like to just return the initial/default value for whatever data type the property uses. I'd like to avoid having to write custom code for each data type, if that's possible.

    Any ideas would be appreciated.

    Friday, July 28, 2006 9:35 PM

All replies

  • You can use generics. ie:

    using System;

    class Sample<T>
     private T _something; // =default(T)
     public T FallThrough  { get { return _something; } }

    class test
     static void Main()
       Sample<string> s1 = new Sample<string>();
       Sample<int> s2 = new Sample<int>();
       Console.WriteLine("Fallthrough1 is {0}", s1.FallThrough == null?"Null":s1.FallThrough);
       Console.WriteLine("Fallthrough2 is {0}", s2.FallThrough);

    Saturday, July 29, 2006 1:03 AM
  • >> The problem is I'm going to have properties with many different data types
    Clarify what you mean by this statement.  It sounds like you want to do something like:

    object FallThrough
                    case 1:
                           return (object) 1;
                    case 2:
                           return (object) 2.0F;
                    case 1:
                           return (object) "Three";

    If that is the case, all I can say is : "IckIckIckIck!!!!  Don't do that!! A proper design will take you about an hour now, and save you days of debugging & maintance later (for example, it would have probably saved you having to ask this question here)"
    Saturday, July 29, 2006 2:26 PM
  • I should have stated that more clearly.  The properties will all have hard-coded types.  However, the class won't just have all integers, for example.  It could have properties of DateTime, String, Decimal, Byte[], etc.  I'm looking for a consistent way to get at the default value for each data type so I don't have to write custom code for each property.

    Someone drew my attention to a new option in VS 2005, which is using "default(dataType)".  That is exactly the type of thing I'm looking for, but unfortunately this code needs to be written for version 1.1 of the framework.

    Saturday, July 29, 2006 6:38 PM