Advanced Study Material for Computer Science: .NET Technology
Explore structured advanced study materials through the Application of .NET Technology Unit 02 C Sharp Basics Notes Set 01. Tailored for learners, utilizing these Computer Science resources ensures thorough preparation and strengthens foundational knowledge before final evaluations.
Practice Computer Science Resources: .NET Technology
Access the complete useful resource PDF for Computer Science below. Regular practice with these targeted academic notes builds familiarity with complex topics and helps secure higher marks in final school evaluations.
These notes introduce C#: its features, program structure, compiling a console program in Visual Studio, data types, variables, literals and constants, and the if, switch and loop statements. They go on to objects and classes, fields, methods, properties, inheritance, encapsulation with access specifiers, polymorphism, constructors and destructors.
Introduction
C# is designed for the Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures.
The following reasons make C# a widely used professional language:
1. It is a modern, general purpose programming language with object oriented and component oriented features.
2. C# is easy to learn and it is a structured language for effective programs.
3. It can be compiled on a variety of computer platforms.
4. It is part of the .NET Framework.
Although C# constructs closely follow traditional high-level languages, C and C++, and being an object-oriented programming language it has a strong resemblance with Java, it has numerous strong programming features that make it endearing to a multitude of programmers worldwide.
Following is the list of a few important features:
1. Boolean Conditions
2. Automatic Garbage Collection
3. Standard Library
4. Assembly Versioning
5. Properties and Events
6. Delegates and Events Management
7. Easy-to-use Generics
8. Indexers
9. Conditional Compilation
10. Simple Multithreading
11. LINQ and Lambda Expressions
12. Integration with Windows
C# Program Structure
Before we study the basic building blocks of the C# programming language, let us look at the bare minimum C# program structure. It consists of a namespace declaration, a class, class methods, class attributes, the Main method, statements and expressions, and comments.
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}It is worth noting the following points:
1. C# is case sensitive, and all statements and expressions must end with a semicolon (;).
2. Every C# program execution starts at the Main method.
3. Unlike Java, the file name can be different from the class name.
Compile and Execute a C# Program
To compile and execute a C# program, follow these steps in Visual Studio:
1. From the menu bar choose File, New and Project.
2. A window will appear. Choose Visual C# from the templates, and then choose Windows.
3. Choose Console Application.
4. Specify a name for your project, and then choose the OK button.
5. The new project appears in Solution Explorer.
6. Write code in the Code Editor.
7. Click the Run button or press the F5 key to run the project.
8. A Command Prompt window appears that contains the line Hello World.
C# Basic Syntax
C# is an object-oriented programming language. In the Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.
The first statement in a C# program is usually "using System;", and the class keyword is used for declaring a class. Comments are used for explaining code. Variables and functions are data members and the task of a specific code.
Data Types
In C# programming the variables are categorized into the following three types: Value types, Reference types and Pointer types.
Value Types
In the C# programming language, value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char and float, which store numbers, alphabets and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.
| Type | Represents | Range | Default Value |
|---|---|---|---|
| bool | Boolean value | True or False | False |
| byte | 8-bit unsigned integer | 0 to 255 | 0 |
| char | 16-bit Unicode character | U+0000 to U+ffff | '\0' |
| decimal | 128-bit precise decimal values with 28-29 significant digits | (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 | 0.0M |
| double | 64-bit double-precision floating point type | (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 | 0.0D |
| float | 32-bit single-precision floating point type | -3.4 x 1038 to +3.4 x 1038 | 0.0F |
| int | 32-bit signed integer type | -2,147,483,648 to 2,147,483,647 | 0 |
| long | 64-bit signed integer type | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 0L |
| sbyte | 8-bit signed integer type | -128 to 127 | 0 |
| short | 16-bit signed integer type | -32,768 to 32,767 | 0 |
| uint | 32-bit unsigned integer type | 0 to 4,294,967,295 | 0 |
| ulong | 64-bit unsigned integer type | 0 to 18,446,744,073,709,551,615 | 0 |
| ushort | 16-bit unsigned integer type | 0 to 65,535 | 0 |
Reference Types
The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using more than one variable, the reference types can refer to the same memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Examples of built-in reference types are: object, dynamic and string.
The Object Type is the ultimate base class for all data types in the C# Common Type System (CTS).
object obj; obj = 100;
The dynamic type can store any type of value in the dynamic data type variable.
dynamic <variable_name> = value; dynamic d = 20;
The String Type allows you to assign any string values to a variable.
string str = "Hello World";
Pointer Types
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as in C or C++. The syntax for declaring a pointer type is:
type* identifier;
For example:
char* cptr; int* iptr;
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows:
1. A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore.
2. The first character in an identifier cannot be a digit.
3. It must not contain any embedded space or symbol like ? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
4. It should not be a C# keyword.
Variables
In C# a variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
The basic value types provided in C# can be categorized as follows:
| Type | Example |
|---|---|
| Integral types | sbyte, byte, short, ushort, int, uint, long, ulong, and char |
| Floating point types | float and double |
| Decimal types | decimal |
| Boolean types | true or false values, as assigned |
| Nullable types | Nullable data types |
Variable Definition in C#
The syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas. Some valid variable definitions are:
int i, j, k; char c, ch; float f, salary; double d;
Variable Initialization in C#
The general form of initialization is:
<data_type> <variable_name> = value;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression. It is a good programming practice to initialize variables properly, otherwise sometimes the program would produce unexpected results. Some examples are:
int d = 3, f = 5; /* initializing d and f. */ byte z = 22; /* initializes z. */ double pi = 3.14159; /* declares an approximation of pi. */ char x = 'x'; /* the variable x has the value 'x'. */
Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for accepting input from the user and storing it into a variable. For example,
int num; num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to the int data type, because Console.ReadLine() accepts the data in string format.
Lvalues and Rvalues in C#
There are two kinds of expressions in C#:
1. Lvalue: an expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
2. Rvalue: an expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and cannot appear on the left-hand side. Following is a valid statement:
int g = 20;
Constants
In C# the constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition.
Integer Literals
An integer literal can be a decimal constant, an octal constant or a hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and no prefix is required for decimal numbers.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals:
212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */
85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. Here are some examples of floating-point literals:
3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */
A signed exponent is introduced by e or E. While representing using decimal form, you must include the decimal point, the exponent, or both; while representing using exponential form you must include the integer part, the fractional part, or both.
Character Constant
Character literals are enclosed in single quotes, e.g., 'x', and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
There are certain characters in C# which, when preceded by a backslash, have a special meaning and are used to represent things like newline (\n) or tab (\t). List of some escape sequence codes:
| Escape sequence | Meaning |
|---|---|
| \\ | \ character |
| \' | ' character |
| \" | " character |
| \? | ? character |
| \a | Alert or bell |
| \b | Backspace |
| \f | Form feed |
| \n | Newline |
| \r | Carriage return |
| \t | Horizontal tab |
| \v | Vertical tab |
| \ooo | Octal number of one to three digits |
| \xhh . . . | Hexadecimal number of one or more digits |
String Literals
String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating the parts using whitespaces. Here are some examples of string literals. All the three forms are identical strings.
"hello, dear" "hello, \ dear" "hello, " "d" "ear"
Defining Constants
Constants are defined using the const keyword. The syntax for defining a constant is:
const <data_type> <constant_name> = value;
The following program demonstrates defining and using a constant in your program:
using System;
class ConstantDemo
{
static void Main()
{
const int LENGTH = 2;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
Console.Write("value of area : {0}", area);
Console.Write(NEWLINE);
}
}When the above code is compiled and executed, it produces the following result:
value of area : 10
Statements
Statements in C# are single entities that cause a change in the program's current state. A statement ends with a semicolon (;), which will generate a compiler error if forgotten. Statements may span multiple lines, which could help make your code more readable.
Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
If Statements
In C# if statements allow evaluation of an expression and, depending on the truth of the evaluation, the capability to branch to a specified sequence of logic. C# provides three forms of if statements: Simple if, If-then-else, and If-else if-else.
Syntax: The syntax of an if statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}Flow of the if statement: the condition is tested; if it is true the conditional code is executed, otherwise control moves past the statement.
If...else Statement
The simple if statement guarantees you can only perform certain actions on a true condition. It's either done or it's not. To handle both the true and false conditions, use the if...else statement. Its syntax in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}Flow of the if...else statement: if the condition is true the if code executes, otherwise the else code executes, and then control continues after the statement.
The if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using a single if...else if statement. The syntax of an if...else if...else statement in C# is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when none of the above conditions is true */
}When using if, else if, else statements there are a few points to keep in mind.
1. An if can have zero or one else's and it must come after any else if's.
2. An if can have zero to many else if's and they must come before the else.
3. Once an else if succeeds, none of the remaining else if's or else's will be tested.
Nested if Statements
In C# it is always legal to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). You can nest else if...else in a similar way as you have nested if statements. The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}Switch Statement
When there are many conditions to evaluate, the if-else if-else statement can become complex and verbose. Sometimes, a much cleaner solution is the switch statement. The switch statement allows testing any integral value or string against multiple values. The syntax for a switch statement in C# is as follows:
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. The following rules apply to a switch statement:
1. The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
2. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
3. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
4. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
5. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
6. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
7. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
using System;
class Program
{
static void Main()
{
int value = 5;
switch (value)
{
case 1:
Console.WriteLine(1);
break;
case 5:
Console.WriteLine(5);
break;
}
}
}Nested Switch Statement
It is possible to have a switch as part of the statement sequence of an outer switch. The syntax for a nested switch statement is as follows:
switch(ch1)
{
case 'A':
Console.WriteLine("This A is part of outer switch");
switch(ch2)
{
case 'A':
Console.WriteLine("This A is part of inner switch");
break;
case 'B': /* inner B case code */
break;
}
break;
case 'B': /* outer B case code */
break;
}Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
C# Loops
In C#, there are four types of loops: While loop, Do loop, For loop and For each loop. Each has its own benefits for certain tasks.
While Loop
There may be a situation when you need to execute a block of code several times. In general, statements are executed sequentially. The syntax of a while loop in C# is:
while(condition)
{
statement(s);
}Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop in C# is:
for(init; condition; increment)
{
statement(s);
}Initialize: this step allows you to declare and initialize any loop control variables.
Condition: the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
Increment (or) Decrement: the condition is now evaluated again. If it is true, the loop executes and the process repeats itself (increment (or) decrement step). After the condition becomes false, the for loop terminates.
Do...while Loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. The syntax of a do...while loop in C# is:
do
{
statement(s);
} while( condition );Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
Nested Loops
C# allows using one loop inside another loop. The syntax for a nested for loop statement in C# is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}The syntax for a nested while loop statement in C# is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}Break Statement
The break statement in C# has the following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. The syntax for a break statement in C# is as follows:
break;
Continue Statement
The continue statement in C# works somewhat like the break statement. The syntax for a continue statement in C# is as follows:
continue;
Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for loop, the continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, the continue statement causes the program control to pass to the conditional tests.
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but programmers more commonly use the for(;;) construct to signify an infinite loop.
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Hey! I am Trapped");
}
}
}
}Designing Objects
From a software perspective, those items selected are referred to as objects, such as a custom class or struct. You would further refine those objects to hold members, which define attributes and behavior.
This session shows you how to create objects and define their members. The attributes and behavior would map to C# language elements. An attribute could be a field or property, and a behavior could be a method or event. This is the world of objects, and by building objects that represent real-world entities, you can build more meaningful systems.
Object Members
In .NET objects are self-contained with a single purpose in mind. All included members should be compatible. Here is a simple class skeleton:
class WebSite
{
// constructors
// destructors
// fields
// methods
// properties
// indexers
// events
// nested objects
}In this example, the class keyword tells that this is a class, a custom reference type. The name WebSite is the name of the class, and the class members are contained within the braces. This could have been a struct instead, but that would have made it a value type.
Instance and Static Members
Each member of an object can be classified in one of two ways: instance member or static member. When a copy of an object is created, it is considered instantiated. At that point, the object exists as a sole entity, with its own set of attributes and behavior. If a second instance of that object were created, it would normally have a separate set of data from that of the first object instance. In C#, object members belong to the instance, unless modified as static. An example of instance objects is a Customer class, where every customer has different information.
Fields
Fields comprise the primary "data" portion of a class. They are the state of an object. They are members of a class as opposed to local variables, which are defined inside of methods and properties.
Constants are efficient. Their values are known at compile time. This enables certain optimizations unavailable to other types of fields. By definition, constants are also static.
Readonly fields are similar to constant fields in that they can't be modified after initialization. The biggest difference between the two is when they're initialized: constants are initialized during compilation, and readonly fields are initialized during runtime.
Methods
Methods are some of the most common object members you'll work with. A C# method is similar to functions, procedures, subroutines, and so on in other programming languages.
void MyMethod()
{
// statements go here
}The preceding method doesn't return any value, which is why you see the void return type. The name is MyMethod, and you would replace that with a meaningful name of what the method does. This method doesn't accept parameters.
Properties
A C# property enables you to protect access to the state of your object. You use them like fields, but they operate much like methods. The following sections show you how to declare and use properties.
Declaring Properties
private string m_description;
public string Description
{
get
{
return m_description;
}
set
{
m_description = value;
}
}The get and set accessors can have any logic you want to define. A get accessor returns a value, and the set accessor sets a value. Notice the value keyword in the set accessor; it holds whatever value was assigned to the property.
static void Main()
{
WebSite site = new WebSite();
site.Description = "cool site";
string desc = site.Description;
}Auto-implemented Properties
public int Rating { get; set; }This Rating property encapsulates some value of type int. Because calling code doesn't have access to the backing store anyway, knowing its name doesn't matter. The C# compiler will create an int field behind the scenes for us.
Indexers
Indexers behave like arrays in that they use the square-bracket syntax to access their members. The .NET collection classes use indexers to accomplish the same goals. Their elements are accessed by index.
Indexers are implemented like properties because they have get and set accessors, following the same syntax. Given an index, they obtain and return an appropriate value with a get accessor. Similarly, they set the value corresponding to the index with the value passed into the indexer.
Designing Object-Oriented Programs
The following sections drill down on these subjects, which are three of the principles of object-oriented programming: Inheritance, Encapsulation, and Polymorphism.
Abstraction is a fourth pillar of object-oriented programming: building objects from a higher-level perspective so that you don't have to be concerned about the lower-level details. In this session, you learn about building objects and managing the public members to create new abstractions.
Inheritance
Inheritance is an object-oriented principle relating to how one class, a derived class, can share the characteristics and behavior from another class, a base class. This can be thought of as an "is a" relationship, because the derived class can be identified by both its class type and its base class type.
The benefits gained by this are the ability to reuse the base class members and to add additional members to the derived class. The derived class then becomes a specialization of the base class (parent). This specialization can continue for as many levels as necessary, each new level derived from the base class above it.
Base Classes
Normal base classes may be instantiated themselves, or inherited. Derived classes inherit each base class member marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Here is an example of a base class:
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
class Customer : Contact
{
public string Gender { get; set; }
public decimal Income { get; set; }
}A derived class declares that it inherits from a base class by adding a colon, :, and the base class name after the derived class name.
Calling Base Class Members
Derived classes can access the members of their base class if those members have protected or greater access. A later section on the object-oriented principle of encapsulation goes into greater depth on access modifiers. A base class member with a protected or public modifier can be accessed by derived classes. Just use the member name as if that member were a part of the derived class itself. Here is an example:
class Contact
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
protected string FullAddress()
{
return Address + '\n' + City + ',' + State + ' ' + Zip;
}
}
class Customer : Contact
{
public string GenerateReport()
{
string fullAddress = FullAddress();
// do some other stuff...
return fullAddress;
}
}In this example, the GenerateReport method of the Customer class calls the FullAddress method in its base class, Contact. All classes have full access to their own members without qualification. Qualification refers to using a class name with the dot operator to access a class member, MyObject.SomeMethod, for instance.
Hiding Base Class Members
When a derived class member has the same name as a corresponding base class member, it is redefining the base class method in the derived class. When using an instance of the derived class, you invoke the derived class's specialized behavior and not the behavior of that method in the base class. In this case, the derived member is said to be "hiding" the base class member. When hiding occurs, the derived member is masking the functionality of the base class member. Users of the derived class won't be able to see the hidden member; they'll see only the derived class member.
Versioning
Versioning, in the context of inheritance, is a C# mechanism that allows modification of classes (creating new versions) without accidentally changing the meaning of the code. Hiding a base class member with the methods previously described generates a warning message from the compiler. This is because of the C# versioning policy. It's designed to eliminate a class of problems associated with modifications to base classes.
Here's the scenario: a developer creates a class that inherits from a third-party library. We assume that the Contact class represents the third-party library.
class Contact
{
// does not include FullAddress() method
}
class WebSite
{
// members
}
public class SiteOwner : Contact
{
WebSite mySite = new WebSite();
public new string FullAddress()
{
string fullAddress = mySite.ToString();
// create an address...
return fullAddress;
}
}Encapsulation
Encapsulation is the object-oriented principle associated with hiding the internals of an object from the outside world. C# has several mechanisms for supporting encapsulation, including properties, indexers, methods, and access modifiers. In this section, you see how to use the features of C# to achieve encapsulation.
Several reasons to take advantage of C#'s built-in mechanisms:
1. Good encapsulation reduces coupling. By clearly defining a public interface (what other code sees) and hiding everything else, users can write code with less dependency on that object.
2. The internal implementation of an object can freely change. This reduces the possibility of breaking someone else's code.
3. An object has a much cleaner interface. Users see only those members that are exposed, which reduces the amount of understanding they need to use the object.
4. It simplifies reuse.
Data Hiding
One of the most useful forms of encapsulation is data hiding. Most of the time, users shouldn't have access to the internal data of an object. Data represents the state of an object, and an object normally has full control of its own state to ensure consistency. Anytime access to data is open, the potential of someone else wreaking havoc with the operation of that object increases.
Sometimes it's logical and necessary to expose object data, especially if it's necessary to expose constants, enumerations, and read-only fields. Perhaps a design goal is to increase the efficiency of data access for a field that's accessed frequently.
Modifiers Supporting Encapsulation
C# manages object encapsulation with appropriate use of C# access modifiers, which specify which code can access class members. They also control the method of access. You apply different sets of access modifiers, depending on whether you are working with objects or object members. You see access modifiers applicable to object members first, followed by which modifiers apply to types.
Public Access Specifier
The public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class. The following example illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
public double length;
public double width;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r. The member functions Display() and GetArea() can also access these variables directly without using any instance of the class. The member function Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r.
Private Access Specifier
The private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members. The following example illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
private double length;
private double width;
public void Acceptdetails()
{
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.
Protected Access Specifier
Protected access is a little less restrictive than private access but more restrictive than public. The only way to use a protected member is via members of the same class or through inheritance. A derived class has full access to protected base class members.
class Contact
{
protected int Age { get; set; }
}
class WebSite
{
// members
}
class Customer : Contact
{
public bool IsContentAppropriate(WebSite site)
{
return Age > 18;
}
}Another feature of this particular example is that the protected member is a property and not a field. This gives Contact the capability to encapsulate its implementation, yet share access at a level necessary for the job. Had the Age information been exposed as a protected field, the coupling between derived classes, such as Customer, would constrain Contact and make maintenance more difficult.
Internal Access Specifier
Internal access restricts visibility to only code within the same assembly. An assembly was briefly described as a unit of deployment, execution, identity and security. An assembly is also a unit of containment where you may restrict access via internal modifiers. Here is an example of internal members:
sealed class CustomerStats
{
internal bool Gender { get; set; }
internal decimal Income { get; set; }
internal int NumberOfVisits { get; set; }
}To use internal access effectively, you create a class library project in Visual Studio. Any code inside of that class library can access your internal members, but other code that references the assembly can't.
Protected Internal Access Specifier
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. Here is an example of the protected internal access specifier. It is also used while implementing inheritance.
class Contact
{
protected internal bool Active { get; set; }
}Polymorphism
The word polymorphism means having many forms. In the object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at compile time. In dynamic polymorphism, it is decided at run time.
Static Polymorphism
In C# the mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. These are function overloading and operator overloading.
Function Overloading
You can have multiple definitions for the same function name in the same scope. The definitions of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
Following is the example where the same function print() is being used to print different data types:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i);
}
void print(double f)
{
Console.WriteLine("Printing float: {0}", f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}Operator Overloading
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names: the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list. For example, look at the following function:
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. Please note the following rules about abstract classes:
1. You cannot create an instance of an abstract class.
2. You cannot declare an abstract method outside an abstract class.
3. When a class is declared sealed, it cannot be inherited; abstract classes cannot be declared sealed.
The following program demonstrates an abstract class:
using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Rectangle : Shape
{
private int length;
private int width;
public Rectangle(int a = 0, int b = 0)
{
length = a;
width = b;
}
public override int area()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}", a);
Console.ReadKey();
}
}
}When the above code is compiled and executed, it produces the following result:
Rectangle class area : Area: 70
Object and Classes
Class
A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition:
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _ Class name [ ( Of typelist ) ] [ Inherits classname ] [ Implements interfacenames ] [ statements ] End Class
Where,
1. attribute list is a list of attributes that apply to the class. Optional.
2. access modifier defines the access levels of the class, it has values as Public, Protected, Friend, Protected Friend and Private. Optional.
3. Shadows indicates that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
4. Must Inherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional.
Object
It is a real time entity. An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. In pure OOP terms an object is an instance of a class.
Example for an object:
public class student
{
}
student objstudent = new student();Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Member variables are attributes of an object (from a design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
In this example we encapsulate some data such as height, width, thickness and the method GetVolume. Other methods or objects can interact with this object through methods that have the public access modifier.
public class Aperture
{
public Aperture()
{
}
protected double height;
protected double width;
protected double thickness;
public double GetVolume()
{
double volume = height * width * thickness;
if (volume < 0)
return 0;
return volume;
}
}Constructors and Destructors
In C# classes have complicated internal structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual.
class C
{
private int x;
private int y;
public C(int i, int j)
{
x = i;
y = j;
}
public void display()
{
Console.WriteLine(x + "i+" + y);
}
}Free study material for Computer Science
Useful Resources and Notes for Computer Science .NET Technology
Comprehensive Study Resources for .NET Technology
Access comprehensive study material for .NET Technology, including revision notes, concept maps, and high-probability questions. These resources are designed in alignment with the latest 2026 CBSE syllabus for Computer Science to support effective exam preparation.
Understanding Marking Schemes
Designed around the official curriculum, these study guides guarantee standard compliance. Reviewing step-by-step solutions clarifies complex sub-topics within .NET Technology and demystifies standard marking schemes for Computer Science evaluations.
Complete Revision for Computer Science
For peak performance in upcoming evaluations, integrate official Computer Science sample papers directly into your study schedule. Follow up your revision by attempting online MCQ tests for .NET Technology to refine calculation speed and precision.
FAQs
The latest 2026-27 advanced study resources for Computer Science are available for free on StudiesToday.com which includes NCERT Exemplars, high-order thinking skills (HOTS) questions, and deep-dive concept summaries.
Our exhaustive Computer Science package includes chapter wise revision notes, solved practice sheets, important formulas and Concept Maps to help in better understanding of all topics.
Yes. For , our resources have been developed to help you get better marks in school exams and also build fundamental strength needed for entrance tests including Competency Based learning.
in , students should use Active Recall method, read the concept summary, then solve the Important Questions section without looking at the answers and then check your answers.
All Computer Science study materials are provided in mobile-friendly PDF. You can download and save them on your device.
Yes, our team has ensured that all Computer Science materials for are strictly aligned with the National Education Policy (NEP) 2020 and the latest 2026-27 syllabus.