CLASSES, OBJECTS AND
OBJECT ORIENTED
PROGRAMMING
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.
Object-oriented programming has several advantages over
procedural programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the C# code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less
code and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing
the repetition of code. You should extract out the codes that are
common for the application, and place them at a single place and
reuse them instead of repeating it.
C# - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.
a class is a template for objects, and an object is an instance of a
class.
When the individual objects are created, they inherit all the
variables and methods from the class.
C# Classes and Objects
Everything in C# is associated with classes and objects, along
with its attributes and methods.
• For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating
objects.
Create a Class
To create a class, use the class keyword:
Create a class named "Car" with a variable color:
class Car
{
string color = "red";
}
Create an Object
An object is created from a class. We have already created the
class named Car, so now we can use this to create objects.
To create an object of Car, specify the class name, followed by the
object name, and use the keyword new:
Example
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
Multiple Objects
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car(); Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}
Using Multiple Classes
using System;
class Car
{
public string color = "red";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
Class Members
Fields and methods inside classes are often referred to as "Class
Members":
Example
Create a Car class with three class members: two fields and one
method.
class MyClass { // The class
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Fields
The variables inside a class are called fields, and that you can
access them by creating an object of the class, and by using the
dot syntax (.).
class Car
{
string color = "red";
int maxSpeed = 200;
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
Object Methods
class Car
{
string color = "red";
int maxSpeed = 200;
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
myObj.fullThrottle(); // Call the method
}
}
C# Constructors
• A constructor is a special method that is used to initialize
objects.
• It is called when an object of a class is created.
• It can be used to set initial values for fields:
Note
The constructor name must match the class name, and it cannot
have a return type (like void or int).
The constructor is called when the object is created.
All classes have constructors by default: if you do not create a
class constructor yourself, C# creates one for you. However, then
you are not able to set initial values for fields.
Constructors save time! Take a look at the last example on this
page to really understand why.
Example :Create a constructor:
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = “Audi; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car();
// Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}
// Outputs “Audi"
Constructor Parameters
class Car
{
public string model;
// Create a class constructor with a parameter
public Car(string modelName)
{
model = modelName;
}
static void Main(string[] args)
{
Car Ford = new Car(“BMW");
Console.WriteLine(Ford.model);
}
}
// Outputs “BMW"
Without constructor:
prog.cs
class Program
{
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
With constructor:
prog.cs
class Program
{
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Car Opel = new Car("Astra", "White", 2005);
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
This keyword
The “this” keyword in C# is used to refer to the current instance of
the class.
It is also used to differentiate between the method parameters
and class fields if they both have the same name.
Another usage of “this” keyword is to call another constructor from
a constructor in the same class.
Here, for an example, we are showing a record of Students i.e: id,
Name, Age, and Subject. To refer to the fields of the current class,
we have used the “this” keyword in C# −
using System.IO;
using System;
class Student {
public int id, age;
public String name, subject;
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
public void showInfo() {
Console.WriteLine(id + " " + name+" "+age+ " "+subject);
}
}
class StudentDetails {
public static void Main(string[] args) {
Student std1 = new Student(001, "Jack", 23, "Maths");
Student std2 = new Student(002, "Harry", 27, "Science");
Student std3 = new Student(003, "Steve", 23, "Programming");
Student std4 = new Student(004, "David", 27, "English");
std1.showInfo();
std2.showInfo();
std3.showInfo();
std4.showInfo();
}
}
Object Arrays: An object array is versatile. They can store an
element of various types in a single collection.
Example: An example that shows how to store an element of a
different type in a single array is as in the following:
using System;
namespace ObjectArray
{
class Program
{
static void Main(string[] args)
{
object[] array=new object[5]{1,1.1111,"Sharad",'c',2.79769};
foreach (var value in array)
{
Console.WriteLine(value);
}
}
}
}
Dynamic Array
Static arrays have the disadvantage that if you have not used a
full array then it will always use the same size as was defined
during its declaration.
We usually need to have an array that we would not know the
values of or how many of them exist.
For that we can use a dynamic array.
A Dynamic Array defines a size of the array at runtime, but then
makes room for new elements in the array during execution.
Declaration and Initialization
List<data type> name= new List<data type>();
e.g;
List<int> list=new List<int>();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DynamicArray
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to C-sharpcorner");
List<int> list=new List<int>();
list.Add(1);
list.Add(10);
list.Add(4);
list.Add(0);
int size = list.Count;
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
list.Sort();
Console.WriteLine("Sorted list values");
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
Console.ReadKey();
}
}
}
NESTED CLASS
A nested class is a class declared in another enclosing class.
It is a member of its enclosing class and the members of an enclosing class have no access to
members of a nested class.
Example
using System;
class One
{
public int num1=5;
public class Two
{
public int num2=10;
}
}
class Demo {
static void Main() {
One a = new One();
Console.WriteLine(++a.num1);
One.Two ab = new One.Two();
Console.WriteLine(++ab.num2);
}
}
C# - Partial Classes and Methods
• In C#, you can split the implementation of a class, a struct, a
method, or an interface in multiple .cs files using the partial
keyword.
• The compiler will combine all the implementation from multiple
.cs files when the program is compiled.
• Consider the following EmployeeProps.cs and
EmployeeMethods.cs files that contain the Employee class.
• EmployeeProps.cs
public partial class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }
}
EmployeeMethods.cs
public partial class Employee
{
//constructor
public Employee(int id, string name)
{
this.EmpId = id;
this.Name = name;
}
public void DisplayEmpInfo()
{
Console.WriteLine(this.EmpId + " " this.Name);
}
}
Example: Combined Class
public class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }
public Employee(int id, string name){
this.EmpId = id;
this.Name = name;
}
public void DisplayEmpInfo(){
Console.WriteLine(this.EmpId + " " this.Name );
}
}
Rules for Partial Classes
• All the partial class definitions must be in the same assembly
and namespace.
• All the parts must have the same accessibility like public or
private, etc.
• If any part is declared abstract, sealed or base type then the
whole class is declared of the same type.
• Different parts can have different base types and so the final
class will inherit all the base types.
• The Partial modifier can only appear immediately before the
keywords class, struct, or interface.
• Nested partial types are allowed.
Partial Methods
• Partial classes or structs can contain a method that split into two
separate .cs files of the partial class or struct.
• One of the two .cs files must contain a signature of the method,
and other file can contain an optional implementation of the partial
method.
• Both declaration and implementation of a method must have the
partial keyword.
• EmployeeProps.cs
public partial class Employee
{
public Employee() {
GenerateEmpId();
}
public int EmpId { get; set; }
public string Name { get; set; }
partial void GenerateEmployeeId();
}
EmployeeMethods.cs
public partial class Employee
{
partial void GenerateEmployeeId()
{
this.EmpId = random();
}
}
Rules for Partial Methods
• Partial methods must use the partial keyword and must return void.
• Partial methods can have in or ref but not out parameters.
• Partial methods are implicitly private methods, so cannot be virtual.
• Partial methods can be static methods.
• Partial methods can be generic.
C# Access Modifiers
The public keyword is an access modifier, which is used to set the
access level/visibility for classes, fields, methods and properties.
C# has the following access modifiers:
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the same class
protected The code is accessible within the same class, or in a
class that is inherited from that class. You will learn more about
inheritance in a later chapter
internal The code is only accessible within its own assembly, but
not from another assembly.
There's also two combinations: protected internal and private
protected.
Static classes and static members
In C#, static means something which cannot be instantiated. You
cannot create an object of a static class and cannot access static
members using an object.
C# classes, variables, methods, properties, operators, events, and
constructors can be defined as static using the static modifier
keyword.
Static Class
Apply the static modifier before the class name and after the access
modifier to make a class static.
The following defines a static class with static fields and methods.
The Calculator class is a static. All the members of it are also static.
You cannot create an object of the static class; therefore the
members of the static class can be accessed directly using a class
name like ClassName.MemberName
C# Static Class
using System;
public static class Calculator
{
private static int _resultStorage = 0;
public static string Type = "Arithmetic";
public static int Sum(int num1, int num2)
{
return num1 + num2;
}
public static void Store(int result)
{
_resultStorage = result;
Console.WriteLine(_resultStorage);
}
}
class Program
{
static void Main(string[] args)
{
var result = Calculator.Sum(10, 25); // calling static method
Calculator.Store(result);
Console.WriteLine(result);
var calcType = Calculator.Type; // accessing static variable
Console.WriteLine(calcType);
Calculator.Type = "Scientific"; // assign value to static variable
Console.WriteLine( Calculator.Type);
}
}
C# Properties (Get and Set)
Properties and Encapsulation
Before we start to explain properties, you should have a basic
understanding of "Encapsulation".
The meaning of Encapsulation, is to make sure that "sensitive"
data is hidden from users. To achieve this, you must:
• declare fields/variables as private
• provide public get and set methods, through properties,
to access and update the value of a private field
Properties
You learned from the previous chapter that private variables can
only be accessed within the same class (an outside class has no
access to it).
However, sometimes we need to access them - and it can be
done with properties.
A property is like a combination of a variable and a method, and it
has two methods: a get and a set method:
Example
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
The Name property is associated with the name field. It is a good
practice to use the same name for both the property and the private
field, but with an uppercase first letter.
The get method returns the value of the variable name.
The set method assigns a value to the name variable. The value
keyword represents the value we assign to the property.
Now we can use the Name property to access and update the
private field of the Person class:
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = “Kumar";
Console.WriteLine(myObj.Name);
}
}
Automatic Properties (Short Hand)
C# also provides a way to use short-hand / automatic properties,
where you do not have to define the field for the property, and you
only have to write get; and set; inside the property.
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
C# Indexers
An indexer is a special type of property that allows a class or a
structure to be accessed like an array for its internal collection. C#
allows us to define custom indexers, generic indexers, and also
overload indexers.
An indexer can be defined the same way as property with this
keyword and square brackets [].
Syntax
<return type> this[<parameter type> index]
{
get{
// return the value from the specified index of an internal
collection
}
set{
// set values at the specified index in an internal collection
}
}
using System;
public class Program
{
public static void Main()
{
StringDataStore strStore = new StringDataStore();
strStore[0] = "One";
strStore[1] = "Two";
strStore[2] = "Three";
strStore[3] = "Four";
for (int i = 0; i < 10; i++)
Console.WriteLine(strStore[i]);
}
}
class StringDataStore
{
private string[] strArr = new string[10]; // internal data storage
public string this[int index]
{
get => strArr[index];
set => strArr[index] = value;
}
}
C# Structs
In C#, classes and structs are blueprints that are used to create instance of a
class.
Structs are used for lightweight objects such as Color, Rectangle, Point etc.
Unlike class, structs in C# are value type than reference type.
It is useful if you have data that is not intended to be modified after creation of
struct.
C# Struct Example
using System;
public struct Rectangle
{
public int width, height;
}
public class TestStructs
{
public static void Main()
{
Rectangle r = new Rectangle();
r.width = 4;
r.height = 5;
Console.WriteLine("Area of Rectangle is: " + (r.width * r.height));
}
}
The Object Class in C#:The Object class is the base class of all
the classes in C#. It has the following methods on C#.
Method & Description
Equals(Object): Determines whether the specified object is equal
to the current object.
Equals(Object,Object,)Determines whether the specified object
instances are considered equal.
Finalize(): Allows an object to try to free resources
GetHashCode(): default hash function.
GetType(): Type of the current instance.
MemberwiseClone():shallow copy of the current Object.
ReferenceEquals(Object,Object): Determines whether the
specified Object instances are the same instance.
ToString(): Returns a string that represents the current object.

classes object fgfhdfgfdgfgfgfgfdoop.pptx

  • 1.
    CLASSES, OBJECTS AND OBJECTORIENTED PROGRAMMING
  • 2.
    C# - Whatis 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. Object-oriented programming has several advantages over procedural programming: • OOP is faster and easier to execute • OOP provides a clear structure for the programs • OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug • OOP makes it possible to create full reusable applications with less code and shorter development time Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.
  • 3.
    C# - Whatare Classes and Objects? Classes and objects are the two main aspects of object-oriented programming. a class is a template for objects, and an object is an instance of a class. When the individual objects are created, they inherit all the variables and methods from the class.
  • 5.
    C# Classes andObjects Everything in C# is associated with classes and objects, along with its attributes and methods. • For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake. A Class is like an object constructor, or a "blueprint" for creating objects. Create a Class To create a class, use the class keyword: Create a class named "Car" with a variable color: class Car { string color = "red"; }
  • 6.
    Create an Object Anobject is created from a class. We have already created the class named Car, so now we can use this to create objects. To create an object of Car, specify the class name, followed by the object name, and use the keyword new: Example class Car { string color = "red"; static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); } }
  • 7.
    Multiple Objects class Car { stringcolor = "red"; static void Main(string[] args) { Car myObj1 = new Car(); Car myObj2 = new Car(); Console.WriteLine(myObj1.color); Console.WriteLine(myObj2.color); } }
  • 8.
    Using Multiple Classes usingSystem; class Car { public string color = "red"; } class Program { static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); } }
  • 9.
    Class Members Fields andmethods inside classes are often referred to as "Class Members": Example Create a Car class with three class members: two fields and one method. class MyClass { // The class // Class members string color = "red"; // field int maxSpeed = 200; // field public void fullThrottle() // method { Console.WriteLine("The car is going as fast as it can!"); } }
  • 10.
    Fields The variables insidea class are called fields, and that you can access them by creating an object of the class, and by using the dot syntax (.). class Car { string color = "red"; int maxSpeed = 200; static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); Console.WriteLine(myObj.maxSpeed); } }
  • 11.
    Object Methods class Car { stringcolor = "red"; int maxSpeed = 200; public void fullThrottle() // method { Console.WriteLine("The car is going as fast as it can!"); } static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); Console.WriteLine(myObj.maxSpeed); myObj.fullThrottle(); // Call the method } }
  • 12.
    C# Constructors • Aconstructor is a special method that is used to initialize objects. • It is called when an object of a class is created. • It can be used to set initial values for fields: Note The constructor name must match the class name, and it cannot have a return type (like void or int). The constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, C# creates one for you. However, then you are not able to set initial values for fields. Constructors save time! Take a look at the last example on this page to really understand why.
  • 13.
    Example :Create aconstructor: // Create a Car class class Car { public string model; // Create a field // Create a class constructor for the Car class public Car() { model = “Audi; // Set the initial value for model } static void Main(string[] args) { Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor) Console.WriteLine(Ford.model); // Print the value of model } } // Outputs “Audi"
  • 14.
    Constructor Parameters class Car { publicstring model; // Create a class constructor with a parameter public Car(string modelName) { model = modelName; } static void Main(string[] args) { Car Ford = new Car(“BMW"); Console.WriteLine(Ford.model); } } // Outputs “BMW"
  • 15.
    Without constructor: prog.cs class Program { staticvoid Main(string[] args) { Car Ford = new Car(); Ford.model = "Mustang"; Ford.color = "red"; Ford.year = 1969; Car Opel = new Car(); Opel.model = "Astra"; Opel.color = "white"; Opel.year = 2005; Console.WriteLine(Ford.model); Console.WriteLine(Opel.model); } } With constructor: prog.cs class Program { static void Main(string[] args) { Car Ford = new Car("Mustang", "Red", 1969); Car Opel = new Car("Astra", "White", 2005); Console.WriteLine(Ford.model); Console.WriteLine(Opel.model); } }
  • 16.
    This keyword The “this”keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name. Another usage of “this” keyword is to call another constructor from a constructor in the same class. Here, for an example, we are showing a record of Students i.e: id, Name, Age, and Subject. To refer to the fields of the current class, we have used the “this” keyword in C# − using System.IO; using System; class Student { public int id, age; public String name, subject;
  • 17.
    public Student(int id,String name, int age, String subject) { this.id = id; this.name = name; this.subject = subject; this.age = age; } public void showInfo() { Console.WriteLine(id + " " + name+" "+age+ " "+subject); } } class StudentDetails { public static void Main(string[] args) { Student std1 = new Student(001, "Jack", 23, "Maths"); Student std2 = new Student(002, "Harry", 27, "Science"); Student std3 = new Student(003, "Steve", 23, "Programming"); Student std4 = new Student(004, "David", 27, "English"); std1.showInfo(); std2.showInfo(); std3.showInfo(); std4.showInfo(); } }
  • 18.
    Object Arrays: Anobject array is versatile. They can store an element of various types in a single collection. Example: An example that shows how to store an element of a different type in a single array is as in the following: using System; namespace ObjectArray { class Program { static void Main(string[] args) { object[] array=new object[5]{1,1.1111,"Sharad",'c',2.79769}; foreach (var value in array) { Console.WriteLine(value); } } } }
  • 19.
    Dynamic Array Static arrayshave the disadvantage that if you have not used a full array then it will always use the same size as was defined during its declaration. We usually need to have an array that we would not know the values of or how many of them exist. For that we can use a dynamic array. A Dynamic Array defines a size of the array at runtime, but then makes room for new elements in the array during execution. Declaration and Initialization List<data type> name= new List<data type>(); e.g; List<int> list=new List<int>();
  • 20.
    using System; using System.Collections.Generic; usingSystem.Linq; using System.Text; namespace DynamicArray { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to C-sharpcorner"); List<int> list=new List<int>(); list.Add(1); list.Add(10); list.Add(4); list.Add(0); int size = list.Count; for (int i = 0; i < list.Count; i++) Console.WriteLine(list[i]); list.Sort(); Console.WriteLine("Sorted list values"); for (int i = 0; i < list.Count; i++) Console.WriteLine(list[i]); Console.ReadKey(); } } }
  • 21.
    NESTED CLASS A nestedclass is a class declared in another enclosing class. It is a member of its enclosing class and the members of an enclosing class have no access to members of a nested class. Example using System; class One { public int num1=5; public class Two { public int num2=10; } } class Demo { static void Main() { One a = new One(); Console.WriteLine(++a.num1); One.Two ab = new One.Two(); Console.WriteLine(++ab.num2); } }
  • 22.
    C# - PartialClasses and Methods • In C#, you can split the implementation of a class, a struct, a method, or an interface in multiple .cs files using the partial keyword. • The compiler will combine all the implementation from multiple .cs files when the program is compiled. • Consider the following EmployeeProps.cs and EmployeeMethods.cs files that contain the Employee class. • EmployeeProps.cs public partial class Employee { public int EmpId { get; set; } public string Name { get; set; } }
  • 23.
    EmployeeMethods.cs public partial classEmployee { //constructor public Employee(int id, string name) { this.EmpId = id; this.Name = name; } public void DisplayEmpInfo() { Console.WriteLine(this.EmpId + " " this.Name); } }
  • 24.
    Example: Combined Class publicclass Employee { public int EmpId { get; set; } public string Name { get; set; } public Employee(int id, string name){ this.EmpId = id; this.Name = name; } public void DisplayEmpInfo(){ Console.WriteLine(this.EmpId + " " this.Name ); } }
  • 25.
    Rules for PartialClasses • All the partial class definitions must be in the same assembly and namespace. • All the parts must have the same accessibility like public or private, etc. • If any part is declared abstract, sealed or base type then the whole class is declared of the same type. • Different parts can have different base types and so the final class will inherit all the base types. • The Partial modifier can only appear immediately before the keywords class, struct, or interface. • Nested partial types are allowed.
  • 26.
    Partial Methods • Partialclasses or structs can contain a method that split into two separate .cs files of the partial class or struct. • One of the two .cs files must contain a signature of the method, and other file can contain an optional implementation of the partial method. • Both declaration and implementation of a method must have the partial keyword. • EmployeeProps.cs public partial class Employee { public Employee() { GenerateEmpId(); } public int EmpId { get; set; } public string Name { get; set; } partial void GenerateEmployeeId(); }
  • 27.
    EmployeeMethods.cs public partial classEmployee { partial void GenerateEmployeeId() { this.EmpId = random(); } } Rules for Partial Methods • Partial methods must use the partial keyword and must return void. • Partial methods can have in or ref but not out parameters. • Partial methods are implicitly private methods, so cannot be virtual. • Partial methods can be static methods. • Partial methods can be generic.
  • 28.
    C# Access Modifiers Thepublic keyword is an access modifier, which is used to set the access level/visibility for classes, fields, methods and properties. C# has the following access modifiers: Modifier Description public The code is accessible for all classes private The code is only accessible within the same class protected The code is accessible within the same class, or in a class that is inherited from that class. You will learn more about inheritance in a later chapter internal The code is only accessible within its own assembly, but not from another assembly. There's also two combinations: protected internal and private protected.
  • 29.
    Static classes andstatic members In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object. C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword. Static Class Apply the static modifier before the class name and after the access modifier to make a class static. The following defines a static class with static fields and methods. The Calculator class is a static. All the members of it are also static. You cannot create an object of the static class; therefore the members of the static class can be accessed directly using a class name like ClassName.MemberName
  • 30.
    C# Static Class usingSystem; public static class Calculator { private static int _resultStorage = 0; public static string Type = "Arithmetic"; public static int Sum(int num1, int num2) { return num1 + num2; } public static void Store(int result) { _resultStorage = result; Console.WriteLine(_resultStorage); } } class Program { static void Main(string[] args) { var result = Calculator.Sum(10, 25); // calling static method Calculator.Store(result); Console.WriteLine(result); var calcType = Calculator.Type; // accessing static variable Console.WriteLine(calcType); Calculator.Type = "Scientific"; // assign value to static variable Console.WriteLine( Calculator.Type); } }
  • 31.
    C# Properties (Getand Set) Properties and Encapsulation Before we start to explain properties, you should have a basic understanding of "Encapsulation". The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must: • declare fields/variables as private • provide public get and set methods, through properties, to access and update the value of a private field Properties You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, sometimes we need to access them - and it can be done with properties. A property is like a combination of a variable and a method, and it has two methods: a get and a set method:
  • 32.
    Example class Person { private stringname; // field public string Name // property { get { return name; } // get method set { name = value; } // set method } } The Name property is associated with the name field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name. The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.
  • 33.
    Now we canuse the Name property to access and update the private field of the Person class: class Person { private string name; // field public string Name // property { get { return name; } set { name = value; } } } class Program { static void Main(string[] args) { Person myObj = new Person(); myObj.Name = “Kumar"; Console.WriteLine(myObj.Name); } }
  • 34.
    Automatic Properties (ShortHand) C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property. class Person { public string Name // property { get; set; } } class Program { static void Main(string[] args) { Person myObj = new Person(); myObj.Name = "Liam"; Console.WriteLine(myObj.Name); } }
  • 35.
    C# Indexers An indexeris a special type of property that allows a class or a structure to be accessed like an array for its internal collection. C# allows us to define custom indexers, generic indexers, and also overload indexers. An indexer can be defined the same way as property with this keyword and square brackets []. Syntax <return type> this[<parameter type> index] { get{ // return the value from the specified index of an internal collection } set{ // set values at the specified index in an internal collection } }
  • 36.
    using System; public classProgram { public static void Main() { StringDataStore strStore = new StringDataStore(); strStore[0] = "One"; strStore[1] = "Two"; strStore[2] = "Three"; strStore[3] = "Four"; for (int i = 0; i < 10; i++) Console.WriteLine(strStore[i]); } } class StringDataStore { private string[] strArr = new string[10]; // internal data storage public string this[int index] { get => strArr[index]; set => strArr[index] = value; } }
  • 37.
    C# Structs In C#,classes and structs are blueprints that are used to create instance of a class. Structs are used for lightweight objects such as Color, Rectangle, Point etc. Unlike class, structs in C# are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C# Struct Example using System; public struct Rectangle { public int width, height; } public class TestStructs { public static void Main() { Rectangle r = new Rectangle(); r.width = 4; r.height = 5; Console.WriteLine("Area of Rectangle is: " + (r.width * r.height)); } }
  • 38.
    The Object Classin C#:The Object class is the base class of all the classes in C#. It has the following methods on C#. Method & Description Equals(Object): Determines whether the specified object is equal to the current object. Equals(Object,Object,)Determines whether the specified object instances are considered equal. Finalize(): Allows an object to try to free resources GetHashCode(): default hash function. GetType(): Type of the current instance. MemberwiseClone():shallow copy of the current Object. ReferenceEquals(Object,Object): Determines whether the specified Object instances are the same instance. ToString(): Returns a string that represents the current object.