In this article we are going to discuss the class in C#. There are many blogs, articles are available on the internet regarding class but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the class in C#.
Class Introduction
Class Bluprint - A Class is like the blueprints for a house. It defines the properties of a house like shape, floors, the works. An Object is more like the house itself. It's the end product built by the properties defined in the Class.
Example
Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties.
A class can be declared using following access specifier which limits the accessibility of classes to other classes.
A Class contains fields, methods, Constructor and properties.
1. Constructoris - A constructoris a method in the class
which gets executed when a class object is created.
2. Field
- A field is a variable of any type. It is basically the data.
3.
Property - A property is a member that provides helps in read and
write of private field.
4. Method - A method is a code
block that contains a series of statements.
Code defined as folowing:
Declaring a Class in C#
A class is defined using the class keyword followed by the class name. The body of the class contains data members (fields or properties) and methods.
In general, class declarations can include these components, in order.
The following code define the declaration of class.
// declaring public class
public class MyClass
{
// Data members (fields)
private int myField;
// Method
public void MyMethod()
{
Console.WriteLine("My Method");
}
}
Types of classes in C#
In C#, classes can be categorized into several types based on their functionality and purpose. Some listed classes name as following:
The below code defines the declaration of various type classes.
public class MyClass
{
// Fields, properties, methods, etc. // Regular Classes
}
public abstract class AbstractClass
{
public abstract void AbstractMethod(); // Abstract Classes
}
public static class UtilityClass
{
public static void DoSomething() { } // Static Classes
}
public partial class PartialClass
{
// Members in this file // Partial Classes
}
// In another file:
public partial class PartialClass
{
// Members in another file
}
public sealed class SealedClass
{
// Members // Sealed Classes
}
public class OuterClass
{
public class NestedClass
{
// Members // Nested Classes
}
}
public class GenericClass
{
// Members // Generic Classes
}
Class Advantage in C#
Classes in C# offer several advantages, There are some of the key advantages of using classes in C# include.