Click here to Skip to main content
13,140,231 members (46,079 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Code Sample:
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 13-Feb-13 5:08am
Updated 23-May-13 20:11pm
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

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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)

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.170915.1 | Last Updated 24 May 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100