1mSnajper
1mSnajper

Reputation: 1

Getting field value by class instance

I learn to write code in C# and I would like to know whether there is an option to get value of the field inside class just by using instance name. I would like it to look like that:

class foo{
   public Int32 field = 35;

   //Code i need... 
} 

public static void Main() {
   foo instance = new foo();
   Console.WriteLine(instance);
}

And the output would be "25". So is there any way to make such code to work or do I need to use for example property?

Upvotes: 0

Views: 340

Answers (1)

Rahul
Rahul

Reputation: 77886

NO, there is not unless you specify the field or property you want to access saying instance.field. Though you can override the ToString() method to print that value like

public override string ToString()
{
  return field.ToString();
}

So now you can say

public static void Main() {
   foo instance = new foo();
   Console.WriteLine(instance); // will print 35
}

Upvotes: 3

Related Questions