Anders Anders - 3 months ago 16
C# Question

Member '<method>' cannot be accessed with an instance reference

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 explanation:


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.

Answer

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.