2

I want to get the default value of a type of a field. I wish to have something like the following code (which of course does not compile):

public class foo
    {
        public int intf;
        public string strf;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(default(foo.intf)); //Expected default(int)
            Console.WriteLine(default(foo.strf)); //Expected default(string)
        }
    }

Is there any way to do that?

ram dvash
  • 190
  • 1
  • 11
  • 6
    you could try doing a search on `reflection` and see how you go? – jazb May 16 '19 at 07:33
  • 3
    If that property/field it's something you know it will be an `int` why wouldn't you directly perform a `default(int)`? Otherwise, as @JohnB says, you could use Reflection to bind the class properties and roam it. – Gonzo345 May 16 '19 at 07:36
  • so the default `value` for `int` is 0. In you class `constructor` you could initialize these to some `well-know` values if this does not suit your needs. – jazb May 16 '19 at 07:38

1 Answers1

5

First you need to reflection in order to get the appropriate fields:

var field = typeof(foo).GetField("intf");

Now you can get the return-type of that field:

var type = field.FieldType

Finally you can get the types default-value, e.g. using this approach from Programmatic equivalent of default(Type):

var default = type.IsValueType ? Activator.CreateInstance(type) : null;
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111