Class is a user defined data type, grouping variables of different data types, methods, properties etc. By default the access modifier of a class is internal, means, the code can be accessed within the current project. However, we can specify the class as public also. Classes can no way be private or protected. These modifiers are used with the class members not with the class.
Note: The compiler will not allow a derived class to be more accessible than its base class. This means that an internal can inherit from a public base, but a public class can't inherit from an internal class.
Example 1: Input user Roll no and name, and display it.
public class student { private int rollno; private string name; public void input() { Console.WriteLine("Enter rollno"); rollno = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter Name"); name = Console.ReadLine(); } public void output() { Console.WriteLine("Your Rollno = " + rollno); Console.WriteLine("\nYour Name = " + name); } } class Program { static void Main(string[] args) { student s = new student(); s.input(); s.output(); Console.ReadLine(); } }
In a situation, where multiple developers need to access to the same class, or in the situation where a code generator, is generating a part of a class, then having the class in multiple files can be beneficial. In that situation, we can use the concept of partial classes.
Example 2: C# Partial Classes
partial class student { int rollno; public void input() { Console.Write("Enter rollno : "); rollno = Convert.ToInt32(Console.ReadLine()); } public void output() { Console.Write("Your rollno = " + rollno); } } partial class student { string name; public void input2() { Console.WriteLine("Enter name"); name = Console.ReadLine(); } public void output2() { Console.Write("Your Name = " + name); } } class Program { static void Main(string[] args) { student s = new student(); s.input(); s.input2(); s.output(); s.output2(); Console.ReadLine(); } }
If a class contains nothing but static methods and properties, the class itself can become static. An instance of the class can never be created. By using the static keyword, the compiler can help by checking that instance members are never accidentally added to the class. If they are, a compile error happens. This can help guarantee that an instance is never created.
Example 3: static classes
static class area { public static void method1() { Console.WriteLine("Method 1"); } } class Program { static void Main(string[] args) { area.method1(); Console.Read(); } }