0% found this document useful (0 votes)
2 views

c# -module3

The document provides an overview of C# and .NET programming concepts, focusing on structures, enumerations, classes, and objects. It explains the differences between structures and classes, detailing their properties, methods, constructors, and destructors. Additionally, it covers object-oriented programming principles such as encapsulation, inheritance, and polymorphism, along with guidelines for implementing these concepts in C#.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

c# -module3

The document provides an overview of C# and .NET programming concepts, focusing on structures, enumerations, classes, and objects. It explains the differences between structures and classes, detailing their properties, methods, constructors, and destructors. Additionally, it covers object-oriented programming principles such as encapsulation, inheritance, and polymorphism, along with guidelines for implementing these concepts in C#.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

C# & .

Net
Module 3 :Structures- Defining a Structure, Assigning Values to Members ,
Structures with Methods, Nested Structures, Classes Vs Structures, Guidelines
to use Structures;
Enumerations- Enumerator Initialization, Enumerator Base Types, Enumerator,
Type Conversion.
Classes and Objects:
Classes, Constructors & Destructors, Nesting of Classes, Members, Properties.
C# - Structures
• In C#, a structure is a value type data type. It helps you to make a
single variable hold related data of various data types.
The struct keyword is used for creating a structure.
• Structures are used to represent a record. Suppose you want to keep
track of your books in a library. You might want to track the following
attributes about each book
• A structure in C# is simply a composite data type consisting of a
number elements of other types.
• A C# structure is a value type and the instances or objects of a
structure are created in stack.
• The structure in C# can contain fields, methods, constants,
constructors, properties, indexers, operators and even other structure
types.
Structure Declaration & Object Creation
Declare struct variable
• Before we use a struct, we first need to create a struct variable. We
use a struct name with a variable to declare a struct variable. For
example,

In the above example, we have created a struct named Employee. Here, we have
declared a variable emp of the struct Employee.
Access C# struct – Method1

We use the struct variable along with the . operator to access


members of a struct. For example,
Method2
Structs & Fields
• A struct in C# can contain fields. These fields can be declared as
private, public, internal. Remember that inside a struct, we can only
declare a field.
• We can't initialize a field inside a struct. However we can use
constructor to initialize the structure fields.
The following is not a valid C# struct and the code will not compile, since the fields
inside the structure are trying to initialize.

struct MyStruct
{
int x = 20; // Error its not possible to initialize
int y = 20; // Error its not possible to initialize
}
• a struct can contain static fields, which can be initialized inside the
struct. The following example shows the use of static fields inside a
struct.

Remember that static fields can't be accessed by an instance of


a struct. We can access them only by using the struct names.
Struct & Methods
using System;
struct MyStruct • A C# struct can also
{ contain methods. The
static int x = 25; methods can be either
static int y = 50; static or non-static.
public void SetXY(int i, int j) {
x = i; • But static methods can
y = j; access only other static
} members and they can't
public static void ShowSum() { invoke by using an object
int sum = x + y;
Console.WriteLine("The sum is {0}", sum);
of the structure. They can
} invoke only by using the
} struct name.
class MyClient {
public static void Main() {
MyStruct ms = new MyStruct();
ms.SetXY(100, 200);
MyStruct.ShowSum();
}
}
Copy Structure:
Create a nested structure
• Nesting of Structures: C# allows the declaration of one structure into another structure and this concept is
termed as the nesting of the structure.
Difference Between Struct And Class In C#
• Struct cannot have a default constructor (a constructor without
parameters) or a destructor.
• Structs are value types and are copied on assignments.
• Structs are value types, while classes are reference types.
• Structs can be instantiated without using a new operator.
• A struct cannot inherit from another struct or class, and it cannot be the
base of a class. All structs inherit directly from the System.ValueType, which
inherits from System.Object.
• Struct cannot be a base class. So, Struct types cannot abstract and are
always implicitly sealed.
• Abstract and sealed modifiers are not allowed, and struct members cannot
be protected or protected internals.
The output will be 20. The value of "b" is a copy of "a", so "b" is unaffected by
change of "a.x". But in class, the output will be 100 because "a" and "b" will
reference the same object.
Enum
• An enum is a special type that represents a group of constants
(unchangeable values).
All the constant names can be declared inside the
curly brackets and separated by a comma.
Enum Values
If values are not assigned to enum members, then the compiler will
assign integer values to each member starting with zero by default.
The first member of an enum will be 0, and the value of each
successive enum member is increased by 1.
• You can assign different values to enum member. A change in the
default value of an enum member will automatically assign
incremental values to the other members sequentially
• You can even assign different values to each member.

The enum can be of any numeric data type


such as byte, sbyte, short, ushort, int, uint,
long, or ulong. However, an enum cannot
be a string type
Access an Enum
Conversion
Class and Objects in C#
• Class:
• A class is simply a user-defined
data type that represents both
state and behavior.
• State tells us how the object
looks or what properties it has.
• Behavior tells us what the
object does
In other words, we can say that a
class is the
blueprint/plan/template that
describes the details of an
object.
object
• Object:
• An object is an identifiable entity with some characteristics, state and
behavior
• For example, we can say ‘Apple’ is an object. Its characteristics are:
round in shape and color is red . Its behavior is: tastes sweet-sour.
Object is an instance of a class. All data members and member
functions of the class can be accessed with the help of objects.
When a class is defined, no memory is allocated, but memory is
allocated when it is instantiated (i.e. an object is created).
Declaring classes
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
Creating objects
Objects can be created by using the new keyword followed by the name of the class, like this:

Customer object1 = new Customer();


How can we create a Class and Object in C#?
Access Class Members using Object
creating multiple objects of one class:
C# Access Modifiers
• 1. public access modifier

When we declare a type or


type member public, it can
be accessed from
anywhere. For example,
2. private access modifier
When we declare a type
member with
the private access modifier,
it can only be accessed
within the
same class or struct.
3. protected access modifier

When we declare a
type member
as protected, it can
only be accessed from
the same class and its
derived classes.
Constructors in C#
• It is a special method present inside a class responsible for initializing
the variables of that class
• The name of the constructor method is exactly the same name as the
class in which it was present. You cannot change the name. If your
class name is Employee, then the name of the constructor method is
going to be Employee
• The constructor method does not return any value. That means it is a
non-value returning method
• Each and every class requires this constructor if we want to create the
instance of that class
It is the responsibility of a programmer to
define the constructor under his class name
and if he fails to do so , on behalf of the
programmer an implicit constructor gets
defined in that class by the compiler
after compilation, the compiler adds the public constructor to the class and
initializes the variable and this is the responsibility of a constructor i.e.
initializing the variables of that class.
• Every variable we declared inside a class and every field we declared inside a
class has a default value. All numeric types are initialized with 0, Boolean types
initialized with false, and string and object types initialized with null.

This is called implicit


constructor , because
defined by compiler
Points
• Implicit constructors are parameter less and this is also called as
default constructors
• Implicit defined constructors are public
Default Constructors in C#
using System;
namespace ConstructorDemo
{
class Employee
{
public int Id, Age;
public string Address, Name;
public bool IsPermanent;
}
class Test
{
static void Main(string[] args)
{
Employee e1 = new Employee();
Console.WriteLine("Employee Id is: " + e1.Id);
Console.WriteLine("Employee Name is: " + e1.Name);
Console.WriteLine("Employee Age is: " + e1.Age);
Console.WriteLine("Employee Address is: " + e1.Address);
Console.WriteLine("Is Employee Permanent: " + e1.IsPermanent);
Console.ReadKey();
}
}
}
Explicit constructor
• One more important point that you need to remember is, how many
instances you created, and that many times the constructor is called
for us
We should not use the word Implicitly while calling
the constructor in C#, why?
Types of Constructors in C#

• There are five types of constructors available in C#, they are as follows
• Default or Parameter Less Constructor
• Parameterized Constructor
• Copy Constructor
C# Parameterized Constructor
• In C#, a constructor can
also accept parameters.
It is called a parameterized
constructor.,
Copy Constructor in C#:
• If we want to create multiple instances with the same values then we
need to use the copy constructor in C#, in a copy constructor the
constructor takes the same class as a parameter to it.

passing one parameter is not a difficult task.


Suppose, the constructor takes 10 or 20
parameters, then it is a time-consuming and
error-prone process to pass the same 10 or 20
parameters. We can overcome this problem by
using Copy Constructor in C#.
we have two constructors as shown in the
image. One constructor takes an int as a
parameter and the other constructor takes the
Copy Constructor type as a parameter.
class Program
{
static void Main(string[] args)
{
CopyConstructor obj1 = new CopyConstructor(10); obj1.Display();
CopyConstructor obj2 = new CopyConstructor(obj1); obj2.Display();
}
}
public class CopyConstructor
{
int x; //Parameterized Constructor
public CopyConstructor(int i)
{
x = i;
} //Copy Constructor
public CopyConstructor(CopyConstructor obj)
{
x = obj.x;
}
public void Display()
{ Console.WriteLine($"Value of X = {x}");
}}}
C# Destructor
In C#, destructor (finalizer) is used to destroy objects of class when the scope of an
object ends. It has the same name as the class and starts with a tilde ~. For example

•A destructor is called implicitly by the


Garbage collector of the .NET
Framework.
• We can only have one destructor in a class.
• A destructor cannot have access modifiers,
Here, ~Test() is the destructor.
parameters, or return types.
• We cannot define destructors in structs.
Static Classes and Static Class Members
• The class which is created by using the static modifier is called a static class in C#. A static class
can contain only static members.
• It is not possible to create an instance of a static class. This is because it contains only static
members.
• A static class cannot be instantiated. All members of a static class are static and are accessed via
the class name directly, without creating an instance of the class.
• Static Data Members: As static class always contains static data
members, so static data members are declared using static keyword
and they are directly accessed by using the class name. The memory
of static data members is allocating individually without any relation
with the object.
• Static Methods: As static class always contains static methods, so
static methods are declared using static keyword. These methods only
access static data members, they can not access non-static data
members.
• All members of a static class are static and are accessed via the class
name directly, without creating an instance of the class
Properties of C#
why the concept of properties came into C#?
• If a class contains any values in it and if we want to access those
values outside of that class, then we can provide access to those
values in 2 different ways. They are as follows:

• By storing the value under a public variable, we can give direct access to the
value outside of the class.
• By storing that value in a private variable, we can also give access to that
value outside of the class by defining a property for that variable.
• Properties are the special type of class members that provides a
flexible mechanism to read, write, or compute the value of a private
field.
• It uses pre-defined methods which are “get” and “set” methods
which help to access and modify the properties.
Where,
• The syntax for Defining Properties: <access_modifier>
can be public,
private, protected
or internal.
<return_type> can
be any valid C#
type.
<property_name>
can be user-
defined.

Get: It returns a single value and it specifies the read-only property.


Set: It will specify the assignment of a value to a private field in a property. It returns a single value and it specifies the write-
only property.
Name property to access
and update
the private field of
the Person class:
Oriented Programming
concepts: Encapsulation,
Polymorphism, Inheritance
C# - What is OOP?
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or methods that
perform operations on the data, while object-oriented programming
is about creating objects that contain both data and methods.
• OOP makes it possible to create full reusable applications with less
code and shorter development time
Encapsulation
• The process of binding or grouping the State (i.e., Data
Members) and Behaviour (i.e., Member Functions) together into a
single unit (i.e., class, interface, struct, etc.) is called Encapsulation in
C#.
• The Encapsulation Principle ensures that the state and behavior of a
unit (i.e., class, interface, struct, etc.) cannot be accessed directly
from other units (i.e., class, interface, struct, etc.).
Example to Understand Encapsulation in C#:
• Every class, interface, struct, enum, etc. that we created is an example
of encapsulation, so let’s create a class called Bank as follows to
understand the encapsulation:

The variables(AccountNumber, Name, and Balance) and


methods(GetBalance, WithdrawAmount, and Deposit) of the class
are bound in a single unit, which is the Bank class. Here, the
encapsulation binds the implementation details of the Bank class
with it and hides it from other classes. If other classes want to access
these details, they need to create the object of the Bank class to
access its data and behavior,
How can we Implement Data Hiding or Data Encapsulation in C#?
• In C#, Data Encapsulation is implemented.
• By declaring the variables as private (to restrict their direct access from outside the class)
• By defining one pair of public setter and getter methods or properties to access private variables from
outside the class.
Inheritance
• Inheritance is a fundamental concept in object-oriented programming
that allows us to define a new class based on an existing class.
• The new class inherits the properties and methods of the existing
class and can also add new properties and methods of its own.
• Inheritance promotes code reuse, simplifies code maintenance, and
improves code organization.
• How to Implement Inheritance in C#?

Why Child Cannot Consume Private Members of Parent?

Generally, Children have rights to their Parent’s Property. As a Child, tomorrow, I can take over my father’s
business. I can take over my Father’s Properties (Car, Buildings, Money, whatever it is). But I cannot take over my
father’s job. The reason is the may be based on his qualifications and his experiences Job whatever my father is
doing
the child class will consume all the members of the Parent class except the private members.
example Here, we have created class A with two public methods,
i.e., Method1 and Method2. Now, I want the same two
methods in another class, i.e., class B. One way to do this
is to copy the above two methods and paste them into
class B as follows.

If we do this, then it is not code re-usability. It is code


rewriting that affects the size of the application. So,
without rewriting, what we need to do is, we need to
perform inheritance
Discussion.
Now, let us add a new method, i.e., Method3 in Class B,
as follows. Inside the Main method, if you see the method
description, it shows that the method belongs to class B.

I can drive my father’s car as if I am the owner, but still,


the registration name is my father. Similarly, class B
can call the methods as the method is its own, but
internally, the methods belong to Class A.
Rules
Rule1:
In C#, the parent classes constructor must be accessible to the child
class; otherwise, the inheritance would not be possible because when
we create the child class object, first it goes and calls the parent class
constructor so that the parent class variable will be initialized and we
can consume them under the child class.
if you are defining an explicit constructor, if
you make that constructor private, and if you
don’t provide an access specifier, then by
default, the class member’s access specifier
is private in C#.

make the class A constructor public;


otherwise, the inheritance would not be
possible.
Rule2:
In inheritance, the child class can access the parent class members, but the parent classes can never
access any members that are purely defined in the child class
• See, according to the law, children have rights to their parents' Property. However, the Parent
does not have rights to the Children’s property. It is only the children’s responsibility to take care
of their parents
• Rule3
We can Initialize a Parent class variable by using the child class instance to make it a reference
variable so that the reference will be consuming the memory of the child class instance.

But in this case, also, we cannot call any


pure child class members using the
reference.
• 1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance

• In single inheritance, a In multilevel inheritance, a In hierarchical inheritance,


single derived class derived class inherits from a multiple derived classes
inherits from a single base and then the same inherit from a single base
base class. derived class acts as a base class.
class for another class
4. Multiple Inheritance 5. Hybrid Inheritance
• In multiple inheritance, a single derived class
inherits from multiple base classes. C# doesn't Hybrid inheritance is a combination of two
support multiple inheritance. However, we or more types of inheritance. The
can achieve multiple inheritance through combination of multilevel and hierarchical
interfaces. inheritance is an example of Hybrid
inheritance.
Example program
Polymorphism
• Polymorphism is one of the fundamental OOP concepts and is a term
used to describe situations where something takes various roles or
forms. In the programming world, these things can be operators or
functions.
• The word polymorphism is derived from two Greek words: poly and
morphs. The word “Poly” means many, and “morphs” means forms.
Therefore, polymorphism means “many forms” or we can say that the
word polymorphism means the ability to take more than one form.
That is one thing that can take many forms.
Real-Time Examples of Polymorphism:
Types of Polymorphism in C#:
What is Compile-Time Polymorphism in C#?
• Method overloading is an example of Static polymorphism. Overloading is the
concept in which method names are the same with different parameters. The
method/function has the same name but different signatures in overloading. It is
also known as Early binding. It is also known as compile-time polymorphism
because the decision of which method is to be called is made at compile time.
Dynamic Polymorphism(Method Overriding in C#)
During inheritance if the same method is present in both the superclass
and the subclass. Then, the method in the subclass overrides the same
method in the superclass. This is called method overriding.
In this case, the same method will perform one operation in the
superclass and another operation in the subclass.
This is achieved through the use of virtual keywords with the method.

You might also like