General information of C# Instance
An object is also called an instance. The object will contain its own set of fields, which can hold values that are different to those of other instances of the class.
class MyClass
{
static void Main()
{
// Create an object of MyRectangle
MyRectangle r = new MyRectangle();
}
}
Fields are variables that hold the state of the object, while methods define what the object can do.
class MyRectangle
{
// Make members accessible for instances of the class
public int x, y;
int GetArea() { return x * y; }
}
The static keyword can be used to declare fields and methods that can be accessed without having to create an instance of the class.
Static (class) members only exist in one copy, which belongs to the class itself, whereas instance (non-static) members are created as new copies for each new object. This means that static methods cannot use instance members since these methods are not part of an instance. On the other hand, instance methods can use both static and instance members.
class MyCircle
{
// Instance variable (one per object)
float r=10;
// Static/class variable (only one copy)
static float pi=3.14 F;
// Instance method
float GetArea()
{
return ComputeArea(r);
}
// Static/class method
static float ComputeArea(float a)
{
return pi*a*a;
}
}