How to create a class in C Sharp 4.0

arunlalds's Avatar, Join Date: Mar 2010
Banned
Problem: You need to create a class declaration.
Code: C#
//default namespace to import, that Visual Studio includes in each file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassSample
{
//public so that it's visible outside of assembly
public class Vertex3d
{
}
}
The class is defined as public, which means it is visible to every other type that references
its assembly. C# defines a number of accessibility modifiers, as detailed as follows: Public= Types members Accessible to everybody, even outside the assembly Private= Types, members Accessible to code in the same type Internal= Types, members Accessible to code in the same assembly Protected= Members, Accessible to code in the same type or derived type Protected Internal= Members Accessible to code in the same assembly internal or a derived class in another assembly If the class does not specify the accessibility, it defaults to internal.
arunlalds's Avatar, Join Date: Mar 2010
Banned
Let's add some usefulness to the Vertex3d class.
Code: C#
public class Vertex3d
{
//fields
private double _x;
private double _y;
private double _z;
//properties
public double X
{
get { return _x; }
set { _x = value; }
}
public double Y
{
get { return _y; }
set { _y = value; }
}
public double Z
{
get { return _z; }
set { _z = value; }
}
//method
public void SetToOrigin()
{
X = Y = Z = 0.0;
}
}
Some notes on the preceding code:
  1. The fields are all declared private, which is good practice in general.
  2. The properties are declared public, but could also be private, protected, or protected internal, as desired.
  3. Properties can have get, set, or both.
  4. In properties, value is the implied argument (that is, in the code).
In the following example, 13.0 would be passed to X in the value argument:
Vertex3d v = new Vertex3d();
v.X = 13.0;
arunlalds's Avatar, Join Date: Mar 2010
Banned
You will often see the following pattern:
Code: C#
class MyClass
{
private int _field = 0;
public int Field { get { return _field; } set { _field = value; } }
}
C# has a shorthand syntax for this:
class MyClass
{
public int Field {get; set;}
//must initialize value in constructor now
public MyClass()
{
this.Field = 0;
}
}
arunlalds's Avatar, Join Date: Mar 2010
Banned
Add the modifying keyword static, as in the following method for adding
two Vertex3d objects:
Code: C#
public class Vertex3d
{
...
public static Vertex3d Add(Vertex3d a, Vertex3d b)
{
Vertex3d result = new Vertex3d();
result.X = a.X + b.X;
result.Y = a.Y + b.Y;
result.Z = a.Z + b.Z;
return result;
}
}
The static method is called like in this example:
Vertex3d a = new Vertex3d(0,0,1);
Vertex3d b = new Vertex3d(1,0,1);
Vertex3d sum = Vertex3d.Add(a, b);
arunlalds's Avatar, Join Date: Mar 2010
Banned
Define a special method, called a constructor, with the same name as the class, with no return type. A constructor runs when a type is created—it is never called directly. Here are two constructors for the Vertex3d class—one taking arguments, the other performing some default initialization.

Code: C#
class Vertex3d
{
public Vertex3d()
{
_x = _y = _z = 0.0;
}
public Vertex3d(double x, double y, double z)
{
this._x =x;
this._y = y;
this._z = z;
}
}
Add a Static Constructor and Initialization
Static fields can be initialized in two ways. One way is with a static constructor, which is similar to a standard constructor, but with no accessibility modifier or arguments:
Code: C#
public class Vertex3d
{
private static int _numInstances;
static Vertex3d()
{
_numInstances = 0;
}
...
}
However, because of performance reasons, it is preferable to initialize static fields inline whenever possible, as shown here:
Code: C#
public class Vertex3d
{
private static int _numInstances = 0;
...
}
arunlalds's Avatar, Join Date: Mar 2010
Banned
Use object initialization syntax, as in the following example:
Code:
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
...
Person p = new Person()
{ Id = 1, Name = “Ben”, Address = “Redmond, WA” };
arunlalds's Avatar, Join Date: Mar 2010
Banned
Both const and read only are used to define data that does not change, but there are important differences: const fields must be defined at declaration. Because of this and the fact that they cannot change value, it implies that they belong to the type as static fields. On the other hand, read only fields can be set at declaration or in the constructor, but nowhere else.
Code:
public class Vertex3d
{
private const string Name = “Vertex”;
private readonly int ver;
public Vertex3d()
{
ver = Config.MyVersionNumber;//Ok
}
public void SomeFunction()
{
ver = 13;//Error!
}
}
arunlalds's Avatar, Join Date: Mar 2010
Banned
Problem: You have multiple constructors, but they have a subset of functionality that is common among them. You want to avoid duplicating code. In C++ and some previous languages, you often had the case where a class with multiple constructors needed to call common initialization code. In these cases, you usually factored out the common code into a common function that each constructor called.
Code:
//C++ example
class MyCppClass
{
public:
MyCppClass() { Init(); }
MyCppClass(int arg) { Init(); }
private:
void Init() { /* common init here*/ };
}
Solution: In C#, you are allowed to call other constructors within the same class
using the this keyword, as shown next:
public class Vertex3d
{
public Vertex3d(double x, double y, double z)
{
this._x = x;
this._y = y;
this._z = z;
}
public Vertex3d(System.Drawing.Point point)
:this(point.X, point.Y, 0)
{
}
...
}
arunlalds's Avatar, Join Date: Mar 2010
Banned
You need to specialize a class by adding and/or overriding
behavior.
Use inheritance to reuse the base class and add new functionality.
Code:
public class BaseClass
{
private int _a;
protected int _b;
public int _c;
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
_a = 1;//not allowed! private in BaseClass
_b = 2;//ok
_c = 3;//ok
}
public void DoSomething()
{
_c = _b = 99;
}
}
Deriving from a class gives access to a base class's public and protected members, but
not private members.
arunlalds's Avatar, Join Date: Mar 2010
Banned
Similar to calling other constructors from the constructor of a class, you can call specific constructors of a base class. If you do not specify a constructor, the base class’s default constructor is called. If the base class’s default constructor requires arguments, you will be required to supply them.
Code:
public class BaseClass
{
public BaseClass(int x, int y, int z)
{ ... }
}
public class DerivedClass : BaseClass
{
public DerivedClass()
: base(1, 2, 3)
{
}
}