tags:

views:

2907

answers:

2

Hi, I am getting into C# and I am having this issue:

namespace MyDataLayer
{
    namespace Section1
    {
        public class MyClass
        {
            public class MyItem
            {
                public static string Property1{ get; set; }
            }
            public static MyItem GetItem()
            {
                MyItem theItem = new MyItem();
                theItem.Property1 = "MyValue";
                return theItem;
            }
        }
     }
 }

I have this code on a UserControl:

using MyDataLayer.Section1;

public class MyClass
{
    protected void MyMethod
    {
        MyClass.MyItem oItem = new MyClass.MyItem();
        oItem = MyClass.GetItem();
        someLiteral.Text = oItem.Property1;
    }
}

Everything works fine, except when I go to access Property1. The intellisense only gives me "Equals, GetHashCode, GetType, and ToString" as options. When I mouse over the oItem.Property1, Visual Studio gives me this explaination:

Member 'MyDataLayer.Section1.MyClass.MyItem.Property1.get' cannot be accessed with an instance reference, qualify it with a type name instead

I am unsure of what this means, I did some googling but wasn't able to figure it out. Can anyone help this newbie out?

thanks, anders

+7  A: 

In C#, unlike VB.NET and Java, you can't access static members with instance syntax. You should do:

MyClass.MyItem.Property1

to refer to that property or remove the static modifier from Property1 (which is what you probably want to do). For a conceptual idea about what static is, see my other answer.

Mehrdad Afshari
What can I do to access it then? what do I need to change around?
Anders
+1  A: 

You can only access static members using the name of the type.

Therefore, you need to either write,

MyClass.MyItem.Property1

Or (this is probably what you need to do) make Property1 an instance property by removing the static keyword from its definition.

Static properties are shared between all instances of their class, so that they only have one value. The way it's defined now, there is no point in making any instances of your MyItem class.

SLaks
Perfect, you solved my problem aswell, Thank you!
Proclyon