Functions & Property Usage in Object Initializers

63 views Asked by At

Does the spec of C# prevent calling a method from within an object's (or struct's) initializer construct?

The reason I'm asking is because I was trying to use a LINQ-to-XML statement to use gater data within the initializer. This does not work. However, if I get the data before hand saved into a local variable it works without issue. I just was wondering why this happens, since I have already figured out the error in my code.

Does Not Work:

SavedData sData = new SavedData()
{
        exportLocation = data.Root.Descendants("ExportLocation").FirstOrDefault().Value,
        exportType = (ExportType)data.Root.Descendants("ExportType").FirstOrDefault().Value
};

Works:

var exLoc = data.Root.Descendants("ExportLocation").FirstOrDefault().Value;
ExportType type = (ExportType)data.Root.Descendants("ExportType").FirstOrDefault().Value;

Saved Data sData = new SavedData()
{
     exportLocation = exLoc,
     exportType = type
};
1

There are 1 answers

1
Nick Bray On BEST ANSWER

You can call methods within initializers, so there is something else going on here.

The following works fine for me:

    class A
    {
        public int x { get; set; }
    }

    class B
    {
        public int foo()
        {
            return 3;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            B data = new B();
            A a = new A() {
                x = data.foo()
            };
        }
    }

a.x gets set to 3, so it works fine.

It might be another problem with your code that was fixed when you rewrote it. It could also be something that the SavedData constructor is doing that is invalidating the data.