Beginning with C# 3.0, you now have auto-implemented Properties where what used to be the standard use of a "backing-field" variable is no longer necessary. If you write this code:
public int a { get; set; }
The compiler will generate a hidden private variable for you.
Here's what your code might look like taking advantage of this:
using System;
namespace ConsoleAccessPrivateMembers
{
internal class MyPrivateClassMem
{
public MyPrivateClassMem()
{
a = 10;
b = 20;
}
public MyPrivateClassMem(int parametera, int parameterb)
{
a = parametera;
b = parameterb;
}
public int a { get; set; }
public int b { get; set; }
public int add()
{
return a + b;
}
}
internal class MyInput
{
private static void Main(string[] args)
{
var obj1 = new MyPrivateClassMem();
obj1.a = 1;
obj1.b = 2;
Console.WriteLine("obj1 add result: " + obj1.add());
var obj2 = new MyPrivateClassMem(100, 200);
Console.WriteLine("obj2 add result: " + obj2.add());
Console.ReadLine();
}
}
}
Note the use of a parameterless Constructor that allows for the initialization of 'a and 'b to default values.
Also note a second, optional, Constructor with parameters supplied, so you can initialize 'a and 'b, if you wish, when you create an instance of the Class 'MyPrivateClassMem.