C# is a powerful and simple general-purpose programming language. It is an object-oriented language, implying objects are created via classes and will have various ranges or visibilities in the development environment. Understanding the default visibilities of classes, nested classes and members is crucial for creating efficient code as per the specified requirements.
A class is the building block of C#. It is used to form object(s), and functions are performed on them which form the base of the whole program or software. The class is what defines the meaning, i.e., the type and scope of the object, and serves as a blueprint. The instance of a class is object
. Other concepts associated with a class are its methods (grouped statements that perform a particular function) and variables (a name given to storage area depending on its type).
Start by mentioning the keyword Class
and then the name of the class. The class body is defined by curly braces, as in the example below:
1<access specifier> class ClassName {
2 // Defining the class, members and variables
3}
Other than the basic declaration, there are some additional attributes that can be specified along with the class definition according to your need.
:
. :
. It is allowed for a class to implement more than one interface.{}
.To familiarize yourself with these concepts, please see the simple example below.
1<public> class StudentInfo {
2 // member variables
3 <public> <int> Rollno;
4 <public> <string> Name;
5 ...
6 <private> <int> primarykey;
7 // member methods
8 <public> <int> firstfunction(int,int) {
9 // define method here
10 }
11 <private> <string> second function(parameter_list) {
12 // define method here
13 }
14 }
The following example will demonstrate all the aspects we have learned so far in the example code.
1using System;
2
3namespace SimpleInterest {
4 class Money {
5 public double income; // Income of First Person in family
6 public double loan; // Income of Second Person in family
7 public double interest; // The interest on a loan to be paid
8 }
9 class Expenses {
10 static void Main(string[] args) {
11 Money Money1 = new Money(); // Declare Money1 of type Money
12 Money Money2 = new Money(); // Declare Money1 of type Money
13 double expense = 0.0; // Store the expenses here
14
15 // Money 1 specification
16 Money1.income = 5000.0;
17 Money1.loan = 600.0;
18 Money1.interest = 0.7;
19
20 // Money 2 specification
21 Money2.income = 10000.0;
22 Money2.loan = 1200.0;
23 Money2.interest = 0.85;
24
25 // Expenses of first person
26 expense = Money1.income - Money1.loan * Money1.interest;
27 Console.WriteLine("Expenses of First Person : {0}", expense);
28
29 // Expenses of second person
30 expense = Money2.income - Money2.loan * Money2.interest;
31 Console.WriteLine("Expenses of Second Person : {0}", expense);
32 Console.ReadKey();
33 }
34 }
35}
At compilation, we get the final result.
1Expenses of First Person : 4580
2Expenses of Second Person : 8980
In the same manner, you can use the live demo feature to write and practice your own code too.
Please note:
Data type
will specify what type of variable it is. Meanwhile, Return Type
is for the data type of the data the method returns, if present.Member functions are called so because they are defined within the class body. Consequently, they have the same prototype as other variables defined in a class. They will operate on the objects that belong to their own class and will have access to all the members of a class for that specific object.
Member Variables are essentially the attributes of a given object. They are private so that encapsulation can be implemented. In C#, encapsulation is the ability of an object to conceal its behavior and the associated data if it is not necessary for the user. Through this property, a set of methods can be considered and acted upon as a single unit. They can be accessed via the public member functions.
To understand the concept of member functions and their scope, let us look at the following example.
1using System;
2
3namespace MoneyApplication {
4 class Money {
5 private double income;
6 private double loan;
7 private double interest;
8
9 public void setIncome( double inc ) {
10 income = inc;
11 }
12 public void setLoan( double lon ) {
13 loan = lon;
14 }
15 public void setInterest( double itr ) {
16 interest = itr;
17 }
18 public double getExpense() {
19 return income * loan * interest;
20 }
21 }
22 class Moneytester {
23 static void Main(string[] args) {
24 Money Money1 = new Money(); // Declare Money1 of type Money
25 Money Money2 = new Money();
26 double expense;
27
28 // Declare Money2 of type Money
29 // Money 1 specification
30 Money1.setIncome(60.0);
31 Money1.setLoan (57.0);
32 Money1.setInterest(0.56);
33
34 // Money 2 specification
35 Money2.setIncome(20.0);
36 Money2.setLoan(24.0);
37 Money2. setInterest (0.09);
38
39 // volume of Money 1
40 expense = Money1.getExpense();
41 Console.WriteLine("Expense of First Person ( Money1) : {0}" ,expense);
42
43 // volume of Money 2
44 expense = Money2.getExpense();
45 Console.WriteLine("Expense of Second Person ( Money2) : {0}", expense);
46
47 Console.ReadKey();
48 }
49 }
50}
A constructor is a special type of class member function which is executed to create a new object of that class. It implements the behavior of that class in the object.
A destructor is also a special type of member function of a particular class executed when the object of its class is going out of scope.
An object is the most basic unit in OOPS and the languages that implement this practice. Once an object is created, it interacts by invoking functions. They can be thought of as the real-life entities in the programming world.
Instantiating a Class: A class is instantiated by creating an object. A given class can have any number of objects.
Initializing an object: The new operator allocates memory for a new object by initiating the class and returns a reference to that memory location.
The C# compiler can differentiate between constructors based on the number of arguments and their types.
In C#, one class can be defined with the definition of another class. These are known as nested classes. They allow the user to clump classes that are used for one purpose logically or together. This enhances encapsulation properties and makes the code more readable and manageable.
For example:
1using System;
2// Outer class
3public class OuterClass {
4 // Method of outer class
5 public void methodA(){
6 Console.WriteLine("Outer class method called");
7 }
8 // Inner class
9 public class InnerClass {
10 // Method of inner class
11 public void methodB() {
12 Console.WriteLine("Inner class Method called");
13 }
14 }
15}
16// Driver Class
17public class Program {
18 // Main method
19 static public void Main(){
20 // Create the instance of outer class
21 OuterClass obj1 = new OuterClass();
22 obj1.methodA();
23
24 /*
25 This statement gives an error because you are not allowed
26 to access inner class methods with outer class objects.
27 obj1. methodB();
28 */
29
30 // Creating an instance of inner class
31 OuterClass.InnerClass obj2 = new OuterClass.InnerClass();
32 // Accessing the method of inner class
33 obj2.methodB();
34 }
35}
The output of this code is:
1Outer class method called
2Inner class Method called
Note:
A nested class can be declared with any access modifier, namely private, public, protected, internal, protected internal, or private protected.
An outer class cannot directly access inner class members, as visible in the example above.
It is possible to create objects of inner class in the outer class.
An inner class is allowed to access a static member declared in outer class. A method is shown below:
1// Main Driver Class
2public class DriverClass {
3 // Main method
4 static public void Main() {
5 // To access the static methodA of the inner class
6 OuterClass1.InnerClass2.methodA();
7 }
8}
Some things to keep in mind with regard to nested classes:
The inner class can access any non-static member that has been declared in the outer class.
Scope of a nested class is limited by the scope of its (outer) enclosing class.
If nothing is specified, the nested class is private (default).
Any class can be inherited into another class in C# (including a nested class).
This article explains how classes are defined in C# and how the scope of different objects can be used for powerful code creation. Armed with this knowledge, anyone can set preferences, permissions for using objects and polymorphism, etc. for fewer lines of code and better performance optimization.
Happy learning C#!