hi,
how can i use private and static member in c# ?
thanks...
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Dec 24, 2012, 10:56 AM
The field is exposed to code outside the class using a public read-only property:
VulpesPosted Dec 24, 2012, 12:45 PM
It can't take parameters and is generally used to initialize static fields in ways which can't be done simply by assigning them constants when they're declared.
So, are you now wanting to make all your fields static rather than instance?
Orhan SALURPosted Dec 24, 2012, 12:40 PM
VulpesPosted Dec 24, 2012, 12:35 PM
You could then call the x() method to print them out:
using System;
class MyClass
{
private string name;
private string surname;
private int number;
public MyClass(string name, string surname, int number)
{
this.name = name;
this.surname = surname;
this.number = number;
}
public void x()
{
Console.WriteLine(name + " " + surname + " " + number);
}
}
class Test
{
static void Main()
{
MyClass mc = new MyClass("Orhan","SALUR", 123456);
mc.x();
Console.ReadKey();
}
}
Orhan SALURPosted Dec 24, 2012, 12:33 PM
Orhan SALURPosted Dec 24, 2012, 12:20 PM
VulpesPosted Dec 24, 2012, 11:33 AM
In fact instance fields are normally declared as private and then exposed to outside code via a public property.
To access a private instance field using reflection, you'll need to change the BindingFlags variable to:
BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic;
and then pass an object reference to the FieldInfo.GetValue method.
Orhan SALURPosted Dec 24, 2012, 11:28 AM
VulpesPosted Dec 24, 2012, 11:21 AM
Suppose in the original example, we don't have the public read-only property. Then, we can still get the value of 'counter' as follows:
Notice that, as there's no object with a static member (it belongs to the class as a whole), we need to pass a null argument to the FieldInfo.GetValue member.
Orhan SALURPosted Dec 24, 2012, 11:09 AM