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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Dec 24, 2012, 5:56 AM EST
The field is exposed to code outside the class using a public read-only property:
Orhan SALUR47 reputationPosted Dec 24, 2012, 6:09 AM EST
VulpesRank #55 · 29.2K reputationPosted Dec 24, 2012, 6:21 AM EST
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 SALUR47 reputationPosted Dec 24, 2012, 6:28 AM EST
VulpesRank #55 · 29.2K reputationPosted Dec 24, 2012, 6:33 AM EST
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 SALUR47 reputationPosted Dec 24, 2012, 7:20 AM EST
Orhan SALUR47 reputationPosted Dec 24, 2012, 7:33 AM EST
VulpesRank #55 · 29.2K reputationPosted Dec 24, 2012, 7:35 AM EST
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 SALUR47 reputationPosted Dec 24, 2012, 7:40 AM EST
VulpesRank #55 · 29.2K reputationPosted Dec 24, 2012, 7:45 AM EST
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?