Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Code Sample:
C#
class MyBaseClass
{
    class MyNestedClass
    {
        String _MyVariable;

        public String MyVariable
        {
            get { return _MyVariable; }
            set { _MyVariable = value; }
        }
    }

    //This one valid
    void MyMethod()
    {
        MyNestedClass objMyClass = new MyNestedClass();
        objMyClass.MyVariable = "";
    }

    //This also valid
    MyNestedClass objMyClass = new MyNestedClass() { MyVariable = "Some Value" };

    //Everyone know, The Below commented code raise the following error, when it will be uncommented.
    //Invalid token 'void' in class, struct, or interface member declaration
    //objMyClass.MyVariable = "Some Value";
}


Without any use of object (objMyClass) outside a method, What is the use of object initializer, in this sample ?
[Note: Please don't mind, if it is a school stuff]
Posted
Updated 23-May-13 20:11pm
v5
Comments
PIEBALDconsult 13-Feb-13 11:21am    
I get "Invalid token '=' in class, struct, or interface member declaration"

Is there a reason you don't want to use the initializer?
Otherwise, set it in a constructor.

What are you trying to do?
Balaganesan Ravichandran 13-Feb-13 11:35am    
@PIEBALDConsult - Corrected, i`m also getting the same error.
Just i want to know why compiler did't raise error when we use object initializer outside a method or what is the use of object initializer outside a method.???

1 solution

It's pretty simple to understand why it gives the error: You are trying to use code outside any method.
If you move the code into a method, then it will work, but the only thing you can put outside a method is a declaration. If you move both lines into a method body, then you can do it - as you have seen with MyMethod.

There are times when you want to declare the object and not set it's properties yet - so the default constructor exists for that. But the object initialiser syntax exists to allow you to specify property values (and you should really make it a property and explicitly mark it public or protected rather than leave it as a default access field) when you declare the class instance, assuming there is no constructor which allows it.

Normally, you would have a specific constructor for the initialisation, but the number of combinations can get too excessive, so the object initializer syntax exists to get round it.
(Generally, I prefer to create specific constructors)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900