Watch before proceed
10. Class & Object
Part-11-C# Static class & Partial class Explained
Static Class
A C# static class is a class that can be declare as static keyword. Suppose if we apply static modifier to a class, then we should not inherited the class. A static class can contain static members only. You can‘t create an object for the static class.
Note :-
- If you declare any field,method as a non-static field,Method, you will get an error "cannot declare instance members in a static class" .
- When you try to create an instance to the static class, it again generates a compile time error, because the static members can be accessed directly with its class name.
- The static keyword is used before the class keyword in a class definition to declare a static class.
- A static class members are accessed by the class name followed by the member name.
- The methods of the static class can be called using the class name without creating the instance.
- we cannot create an object of that class using the new keyword
Example-1
public static string name;
public static string Address;
// Static method
// Static method
public static void Test()
{
name = "chandan";
Address = "Delhi";
}
}
class Program
{
{
Console.WriteLine("My Name is" + Demo.name);
Console.WriteLine("My Name is" + Demo.Address);
}
}
Partial Class
Syantax:
public partial class Program
{
//Code
}
Advantage:
- Multiple developers can also work simultaneously like one creating logic and other working on designer part.
- It allows us to write partial class, interface, struct and method in two or more separate source files and compile it as a single unit.
- Larger classes can be split into smaller classes for easy to understand and maintain.
public partial class Demo
{
private int x;
private int y;
public Demo(int x, int y) {
this.x = x;
this.y = y;
}
}
public partial class Demo
{
public void PrintCoords()
{
Console.WriteLine("Coords: {0},{1}", x, y);
Console.WriteLine("Execute the Second Partial class");
}
}
{
private int x;
private int y;
public Demo(int x, int y) {
this.x = x;
this.y = y;
}
}
public partial class Demo
{
public void PrintCoords()
{
Console.WriteLine("Coords: {0},{1}", x, y);
Console.WriteLine("Execute the Second Partial class");
}
}
Demo demo=new Demo(10,24);
demo.PrintCoords();
Console.WriteLine("Press any key to exit.");
Console.Read();
}
}