Operator overloading allows operators like +, -, *, etc. to be used with user-defined types by defining specific method implementations. It enables operations on user-defined classes to behave similarly to built-in types. The document provides examples of overloading unary and binary operators in C# classes to change the sign of a number and add two calculator objects respectively. It also discusses the different operators that can and cannot be overloaded and how to define the operator overloading methods with the correct return types and parameters.
Learn about the basic fundamentals of java and important for the different company's interview. Topics like JRE, JDK, Java Keywords, Primitive DataTypes, Types of Variables, Logical, Shift and Bitwise Operator working, Command Line Argument, Handling Arrays, Array Copy, and different programs and output based programs.
Learn about the basic fundamentals of java and important for the different company's interview. Topics like JRE, JDK, Java Keywords, Primitive DataTypes, Types of Variables, Logical, Shift and Bitwise Operator working, Command Line Argument, Handling Arrays, Array Copy, and different programs and output based programs.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Memory management in Swift is fairly abstracted away from you as a developer and it’s easy to build iOS apps without an understanding of it… until something goes wrong. This can result in unexpected behavior, unclear error messages, lost data and crashes. Even a basic understanding of memory management can go a long way, making it easy to prevent these issues in the first place, understand what when wrong when they do occur and know how to fix them.
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
Advanced Scala reflection & runtime meta-programming. The Scala compiler toolbox. Reading Scala Annotations and overcoming type erasure with some real world use cases.
This presentation is an introduction to Dotty / Scala 3.
It covers the features which I deem most important for Scala developers.
For detailed information see the [Dotty documentation](https://dotty.epfl.ch/docs/index.html).
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Memory management in Swift is fairly abstracted away from you as a developer and it’s easy to build iOS apps without an understanding of it… until something goes wrong. This can result in unexpected behavior, unclear error messages, lost data and crashes. Even a basic understanding of memory management can go a long way, making it easy to prevent these issues in the first place, understand what when wrong when they do occur and know how to fix them.
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
Advanced Scala reflection & runtime meta-programming. The Scala compiler toolbox. Reading Scala Annotations and overcoming type erasure with some real world use cases.
This presentation is an introduction to Dotty / Scala 3.
It covers the features which I deem most important for Scala developers.
For detailed information see the [Dotty documentation](https://dotty.epfl.ch/docs/index.html).
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
Certainly, here's a brief explanation of constructors, destructors, and operator overloading without using code:
Constructors: Constructors are special methods used to initialize objects of a class. They set the initial state of an object when it is created.
Destructors: Destructors are special methods used to clean up resources and perform necessary cleanup when an object is no longer needed or goes out of scope. They ensure proper resource management.
Operator Overloading: Operator overloading is a feature that allows you to define custom behaviors for operators such as +, -, *, /, etc., when they are applied to objects of your class. It enables you to work with objects in a way that is meaningful for your specific class.
Constructors can be of different types:
Default Constructors: Initialize objects with default values.
Parameterized Constructors: Accept arguments to initialize objects with specific values.
Copy Constructors: Create a new object as a copy of an existing object.
Constructor Overloading: A class can have multiple constructors with different parameter lists, providing flexibility in object initialization.
Destructors are executed automatically when an object is destroyed. They are essential for releasing resources like memory, file handles, or network connections, ensuring proper cleanup and preventing resource leaks.
Operator overloading enables you to define how operators work with objects of your class. For instance, you can specify what the + operator does when applied to two objects of your class, allowing for custom operations that make sense in the context of your class's functionality.
In summary, constructors initialize objects, destructors handle cleanup, and operator overloading allows custom operations with operators when working with objects. These features are crucial for building custom classes in object-oriented programming.
ZeroSpace is a part of Woxa Technology where industrial trainer are ready to trained you.Take a demo class and choose your future in the programming field. We offer to learn in latest technology with live project which is demanding.
feel free to contact us-: 8471003400
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
2. Operator Overloading
The concept of overloading a function can also
be applied to operators. Operator overloading
gives the ability to use the same operator to do
various operations. It provides additional
capabilities to C# operators when they are
applied to user-defined data types. It enables to
make user-defined implementations of various
operations where one or both of the operands
are of a user-defined class.
4. Overloading ability of the various
operators
OPERATORS DESCRIPTION
+, -, !, ~, ++, – –
unary operators take one operand and
can be overloaded.
+, -, *, /, %
Binary operators take two operands
and can be overloaded.
==, !=, =
Comparison operators can be
overloaded.
&&, ||
Conditional logical operators cannot
be overloaded directly
+=, -+, *=, /=, %=, =
Assignment operators cannot be
overloaded.
5. //WAP to change the sign using unary operatot
class Calculator
{
public int number1;
public Calculator(int num1)
{
number1 = num1;
}
// Function to perform operation
// By changing sign of integers
public static Calculator operator -(Calculator c1)
{
c1.number1 = -c1.number1;
Console.WriteLine("From class"+c1.number1);
return c1;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator(15);
calc = -calc;
Console.ReadKey();
}
}
6. uing System;
namespace BinaryOverload
{
class Calculator
{
public int number = 0;
public Calculator()
{
}
public Calculator(int n)
{
number = n;
}
// Overloading of Binary "+" operator
public static Calculator operator +(Calculator Calc1,Calculator Calc2)
{
Calculator Calc3 = new Calculator();
Calc3.number = Calc2.number + Calc1.number;
return Calc3;
}
// function to display result
public void display()
{
Console.WriteLine("{0}", number);
}
}
class CalNum
{
static void Main(string[] args)
{
Calculator num1 = new Calculator(200);
Calculator num2 = new Calculator(40);
Calculator num3 = new Calculator();
num3 = num1 + num2;
num1.display();
num2.display();
num3.display();
Console.ReadKey();
}
}
}
7. NOTE
• The return type can be of any type except void
for unary operators like !, ~, + and dot (.)
• The return type must be the type of ‘Type’ for
– and ++ operators.
8. INHERITANCE
• Acquiring (taking) the properties of one class
into another class is called inheritance.
Inheritance provides reusability by allowing us
to extend an existing class.
• The reason behind OOP programming is to
promote the reusability of code and to reduce
complexity in code and it is possible by using
inheritance.
12. NOTE
• C# do not support multiple inheritance to
aviod Ambiguity . In multiple inheritance, you
have a derived class which inherits two base
classes Diamond problem
13. • Default Superclass: Except Object class, which
has no superclass, every class has one and
only one direct superclass(single inheritance).
• Superclass can only be one: A superclass can
have any number of subclasses. But a subclass
can have only one superclass.
14. using System;
namespace ConsoleApplication1
{
// Base class
class STD
{
// data members
public string name;
public string subject;
// public method of base class
public void readers(string name, string subject)
{
this.name = name;
this.subject = subject;
Console.WriteLine("Myself: " + name);
Console.WriteLine("My Favorite Subject is: " + subject);
}
}
class IT : STD
{
// constructor of derived class
public IT()
{
Console.WriteLine("IT students");
}
}
class PROGRAM
{
// Main Method
static void Main(string[] args)
{
// creating object of derived class
IT i = new IT();
// calling the method of base class
// using the derived class object
i.readers("XYZ", "C#");
Console.ReadKey();
}
}
}
15. C# Constructor
In C#, constructor is a special method which is
invoked automatically at the time of object
creation. It is used to initialize the data members
of new object generally. The constructor in C#
has the same name as class or struct.
There can be two types of constructors in C#.
• Default constructor
• Parameterized constructor
16. C# Default Constructor
A constructor which has no argument is known
as default constructor. It is invoked at the time
of creating object.
C# Parameterized Constructor
A constructor which has parameters is called
parameterized constructor. It is used to provide
different values to distinct objects.
17. //Program for constructor overloading
using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int i, String n, float s)
{
id = i;
name = n;
salary = s;
}
public void display()
{
Console.WriteLine(id + " " + name + " " + salary);
}
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
}
class TestEmployee
{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "xyz", 890000f);
Employee e2 = new Employee(102, "Mhh", 490000f);
Employee e3 = new Employee();
e1.display();
e2.display();
e3.display();
}
}
18. C# Destructor
A destructor works opposite to constructor, It destructs
the objects of classes. It can be defined only once in a
class. Like constructors, it is invoked automatically.
Note: C# destructor cannot have parameters. Moreover,
modifiers can't be applied on destructors.
• ~Employee()
• {
• Console.WriteLine("Destructor Invoked");
• }
19. this
in C#
In c# programming, this is a keyword that refers to
the current instance of the class. There can be 3
main usage of this keyword in C#.
• It can be used to refer current class instance
variable. It is used if field names (instance
variables) and parameter names are same, that is
why both can be distinguish easily.
• It can be used to pass current object as a
parameter to another method.
• It can be used to declare indexers.
20. using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int id, String name,float salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sss", 890000f);
Employee e2 = new Employee(102, "Mmm", 490000f);
e1.display();
e2.display();
}
}
21. C# static
When a member is declared static, it can be accessed
with the name of its class directly.
Static is a modifier in C# which is applicable for the
following:
• Classes
• Variables
• Methods
• Constructor
It is also applicable to properties, event, and operators.
22. Program count number of object
• using System;
• public class Account
• {
• public int accno;
• public String name;
• public static int count=0;
• public Account(int accno, String name)
• {
• this.accno = accno;
• this.name = name;
• count++;
• }
•
• public void display()
• {
• Console.WriteLine(accno + " " + name);
• }
• }
• class TestAccount{
• public static void Main(string[] args)
•
• Account a1 = new Account(101, "Ssss");
• Account a2 = new Account(102, "Mmm”);
• Account a3 = new Account(103, "Aaaa”);
• a1.display();
• a2.display();
• a3.display();
• Console.WriteLine("Total Objects are: "+Account.count);
• }
• }
23. Sealed Class
Sealed classes are used to restrict the inheritance
feature of object oriented programming. Once a class is
defined as a sealed class, this class cannot be inherited.
In C#, the sealed modifier is used to declare a class
as sealed
• // Sealed class
• sealed class SealedClass
• {
• }
24. C# static class
The C# static class is like the normal class but it
cannot be instantiated. It can have only static
members
• C# static class contains only static members.
• C# static class cannot be instantiated.
• C# static class is sealed.
• C# static class cannot contain instance
constructors.
25. //Static class
• using System;
• public static class MyMath
• {
• public static float PI=3.14f;
• public static int cube(int n){return n*n*n;}
• }
• class TestMyMath{
• public static void Main(string[] args)
• {
• Console.WriteLine("Value of PI is: "+MyMath.PI);
• Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));
• }
• }
26. C# static constructor
C# static constructor is used to initialize static
fields. It can also be used to perform any action
that is to be performed only once. It is invoked
automatically before first instance is created or
any static member is referenced.
• C# static constructor cannot have any modifier
or parameter.
• C# static constructor is invoked implicitly. It
can't be called explicitly.
27. //static constructor
• using System;
• public class Account
• {
• public int id;
• public String name;
• public static float rateOfInterest;
• public Account(int id, String name)
• {
• this.id = id;
• this.name = name;
• }
• static Account()
• {
• rateOfInterest = 9.5f;
• }
• public void display()
• {
• Console.WriteLine(id + " " + name+" "+rateOfInterest);
• }
• }
• class TestEmployee{
• public static void Main(string[] args)
• {
• Account a1 = new Account(101, "Sonoo");
• Account a2 = new Account(102, "Mahesh");
• a1.display();
• a2.display();
•
• }
• }
28. Properties
A property is like a combination of a variable and a
method, and it has two methods: a get and a set
method
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
29. • using System;
• public class Employee
• {
• private string name;
•
• public string Name
• {
• get
• {
• return name;
• }
• set
• {
• name = value;
• }
• }
• }
• class TestEmployee{
• public static void Main(string[] args)
• {
• Employee e1 = new Employee();
• e1.Name = “C# is bestl";
• Console.WriteLine("Employee Name: " + e1.Name);
•
• }
• }
30. Abstract classes are the way to achieve
abstraction in C#. Abstraction in C# is the
process to hide the internal details and
showing functionality only. Abstraction can be
achieved by two ways:
• Abstract class
• Interface
Abstract class and interface both can have
abstract methods which are necessary for
abstraction.
31. Abstract classes
Abstract classes, marked by the
keyword abstract in the class definition, are
typically used to define a base class in the
hierarchy. What's special about them, is that
you can't create an instance of them - if you try,
you will get a compile error. Instead, you have to
subclass them, and create an instance of your
subclass. It can have abstract and non-abstract
methods.
32. Abstract Method
A method which is declared abstract and has no
body is called abstract method. It can be
declared inside the abstract class only. Its
implementation must be provided by derived
classes.
33. using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
34. Interface
• Interface in C# is a blueprint of a class. It is like
abstract class because all the methods which
are declared inside the interface are abstract
methods. It cannot have method body and
cannot be instantiated.
• It is used to achieve multiple
inheritance which can't be achieved by class.
It is used to achieve fully abstraction because
it cannot have method body.
35. • Interfaces specify what a class must do and not how.
• Interfaces can’t have private members.
• By default all the members of Interface are public and
abstract.
• The interface will always defined with the help of
keyword ‘interface‘.
• Interface cannot contain fields because they represent
a particular implementation of data.
• Multiple inheritance is possible with the help of
Interfaces but not with classes.
37. WHAT IS EXCEPTION?
Before starting to learn Exception handling, it is necessary
to know what actually Exception is and why it is
necessary to learn exception handling. Exception stands
for programming error which appears at runtime. For
example, you have made a program in which user inputs
two numbers and program divide the number and show
output. Now consider what happens if user input zeroes
as a second or first number. As we all know that any
number divided by zero returns infinite. In this condition,
your program breaks unconditionally by showing
DivideByZeroException. To handle any runtime error you
must keep your code under exception handling block.
38. Exception Handling gives a way to control
runtime programming error in a structured and
controlled manner. If any runtime error appears
the handler shows easy readable message
telling user what the problem is and continue
the program.
39. HOW TO HANDLE EXCEPTION AT
RUNTIME?
All the exception handling is based on only four keywords: try,
catch, throw and finally. All Exception class is derived
from System.Exception namespace.
• try: try keyword is used for identifying code block which
may cause exception at runtime.
• catch: catch keyword handle the exception if try block
raises exception. The code under try block if raises runtime
error, try block sends handler to catch block to handle error.
• throw: throw keyword is used for creating user defined
exception messages.
• finally: finally block executed whether exception is raised
or not. It is used for cleaning resource and executing set of
code.
40. TRY CATCH FINALLY
Try Catch Finally is the basic building block of
exception handling in c#. 'Try' block keeps the
code which may raise exception at runtime.
The 'catch' block handle the exception if try
block gets error and 'finally' block executes
always whether exception is raised or not. A try
block may have multiple catch blocks
41. using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exception_Handling
{
class Program
{
static void Main(string[] args)
{
label:
// Try block: The code which may raise exception at runtime
try
{
int num1, num2;
decimal result;
Console.WriteLine("Divide Program. You Enter 2 number and we return result");
Console.WriteLine("Enter 1st Number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter 2nd Number: ");
num2 = Convert.ToInt32(Console.ReadLine());
result = (decimal)num1 / (decimal)num2;
Console.WriteLine("Divide : " + result.ToString());
Console.ReadLine();
}
42. //Multiple Catch block to handle exception
catch (DivideByZeroException dex)
{
Console.WriteLine("You have Entered 0");
Console.WriteLine("More Details about Error: nn" + dex.ToString() + "nn");
goto label;
}
catch (FormatException fex)
{
Console.WriteLine("Invalid Input");
Console.WriteLine("More Details about Error: nn" + fex.ToString() + "nn");
goto label;
}
//Parent Exception: Catch all type of exception
catch (Exception ex)
{
Console.WriteLine("Othe Exception raised" + ex.ToString() + "nn");
goto label;
}
//Finally block: it always executes
finally
{
Console.WriteLine(" For Exit Press Enter ");
Console.ReadLine();
}
}
}
}
43. User defined exception
using System;
namespace u1
{
class Program
{
static void Main(string[] args)
{
int acceptorder;
Console.WriteLine("Welcome to Shopping Site:nHow many books you want to buy (max 10):");
acceptorder = Convert.ToInt32(Console.ReadLine());
try
{
if (acceptorder == 10 || acceptorder < 10)
{
Console.WriteLine("Congratulations! You have bought {0} books", acceptorder);
Console.ReadLine();
}
else
{
throw (new maxlimit(" The number of item you want to buy is out of stock."));
}
}
catch (maxlimit m)
{
Console.WriteLine(m.Message.ToString());
Console.ReadLine();
}
}
}
//Creating Custome Exception - OutofStockException
public class maxlimit : Exception
{
public maxlimit (string message): base(message)
{
Console.WriteLine("hell"
}
}
}
44. WHAT IS SYSTEM EXCEPTION?
System Exception is predefined Exception class
in C# that is ready to use in programming. Just
choose which exception may occur in your code
and use it in a catch block.
45. Checked And Unchecked
// SAMPLE TO EXPLAIN CONCEPT
using System;
namespace Checked_Unchecked
{
class Program
{
static void Main(string[] args)
{
sbyte num1 = 20, num2 = 30, result;
result = (sbyte)(num1 * num2);
Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
Console.ReadKey();
}
}
}
//The size of sbyte is -128 to 127 only; so the result is overflowed.
46. Checked strictly monitor your code and if any
overflow exception generated it sends control to
catch for handling exception.
Unchecked statement ignores overflow
exception and shows output.
47. EXAMPLE of checked and unchecked
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Checked_Unchecked
{
class Program
{
static void Main(string[] args)
{
sbyte num1 = 20, num2 = 30, result;
try
{
unchecked
{
result = (sbyte)(num1 * num2);
Console.WriteLine("from unchecked {0} x {1} = {2}", num1, num2, result);
}
checked
{
result = (sbyte)(num1 * num2);
Console.WriteLine("from checked {0} x {1} = {2}", num1, num2, result);
}
}
catch (OverflowException oex)
{
Console.WriteLine(oex.Message);
}
Console.ReadKey();
}
}
}
48. Write a program to handle NullReferenceException and fix the error message "Object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Null_Reference_Exception
{
class Program
{
static void Main(string[] args)
{
string text = null;
try
{
int length = text.Length;
Console.WriteLine(length);
Console.ReadLine();
}
catch (NullReferenceException nex)
{
Console.WriteLine(nex.Message);
}
Console.ReadLine();
}
}
}
49. Encapsulation And Abstraction
Encapsulation and abstraction is the advanced
mechanism in C# that lets your program to hide
unwanted code within a capsule and shows only
essential features of an object. Encapsulation is
used to hide its members from outside class or
interface, whereas abstraction is used to show
only essential features.
50. What is Access Specifiers in C#?
Access Specifiers defines the scope of a class
member. A class member can be variable or
function. In C# there are five types of access
specifiers are available.
List of Access Specifiers
• Public Access Specifiers
• Private Access Specifiers
• Protected Access Specifiers
• Internal Access Specifiers
• Protected Internal Access Specifiers.
51. • Public Access Specifiers
The class member, that is defined as a public can be accessed by other class members that are initialized outside the class. A
public member can be accessed from anywhere even outside the namespace
Private Access Specifiers (C#)
The private access specifiers restrict the member variable or function to be called outside of the parent class. A private function or
variable cannot be called outside of the same class. It hides its member variable and method from other class and methods
Protected Access Specifiers
The protected access specifier hides its member variables and functions from other classes and objects. This type of variable or
function can only be accessed in child class. It becomes very important while implementing inheritance.
C# Internal Access Specifiers
The internal access specifier hides its member variables and methods from other classes and objects, that is resides in other
namespace. The variable or classes that are declared with internal can be access by any member within application
C# Protected Internal Access Specifiers
The protected internal access specifier allows its members to be accessed in derived class, containing class or classes within same
application. However, this access specifier rarely used in C# programming but it becomes important while implementing
inheritance.
52. Get Set Modifier
• Properties are an extension of fields and are accessed
using the same syntax. They use accessors through
which the values of the private fields can be read,
written or manipulated.
• The get set accessor or modifier mostly used for
storing and retrieving the value from the private field.
• In simple word, the get method used for retrieving the
value from private field whereas set method used for
storing the value in private variables.
53. namespace Get_Set
{
class access
{
// String Variable declared as private
private static string name;
public void print()
{
Console.WriteLine("nMy name is " + name);
}
public string Name //Creating Name property
{
get //get method for returning value
{
return name;
}
set // set method for storing value in name field.
{
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{
access ac = new access();
Console.Write("Enter your name:t");
// Accepting value via Name property
ac.Name = Console.ReadLine();
ac.print();
Console.ReadLine();
}
}
}
•
54. Classes And Methods In C#
• A class in C# is a blueprint or template that is
used for declaring an object. However, there is no
need to declare an object of the static class. A
class consists of member variables, functions,
properties etc. A method is a block of code in C#
programming. The function makes program
modular and easy to understand.
• In object oriented programming, classes and
methods are the essential thing. It provides
reusability of code and makes c# programming
more secure.
55. Example of class
namespace Creating_Class
{
class accept //Creating 1st. class
{
public string name;
public void acceptdetails()
{
Console.Write("Enter your name:t");
name = Console.ReadLine();
}
}
class print // Creating 2nd class
{
public void printdetails()
{
//Creating object of 1st. class
accept a = new accept();
//executing method of 1st class.
a.acceptdetails();
//Printing value of name variable
Console.WriteLine("e;Your name is "e; + a.name);
}
}
class Program //Creating 3rd class
{
static void Main(string[] args)
{
print p = new print();
p.printdetails();
Console.ReadLine();
}
}
}
56. Static Method And Variables
Whenever you write a function or declare a variable, it doesn’t create an instance in a memory until you create an object of the class. But if you declare any
function or variable with a static modifier, it directly creates an instance in a memory and acts globally. The static modifier doesn't reference any object.
//Power of a number using static
using System;
namespace Static_var_and_fun
{
class number
{
// Create static variable
public static int num;
//Create static method
public static void power()
{
Console.WriteLine("Power of {0} = {1}", num, num * num);
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a numbert");
number.num = Convert.ToInt32(Console.ReadLine());
number.power();
}
}
}
57. WHY THE MAIN METHOD IS ALWAYS DECLARED WITH STATIC?
The Main method in C# is always declared with static because it
can’t be called in another method of function.
The Main method instantiates other objects and variables but
there is no any method there that can instantiate the main
method in C#.
On another hand, the main method doesn’t accept parameter
from any other function. It only takes a parameter as an
argument via command line argument.
58. Command Line Argument
• Parameter(s) can be passed to a Main() method in C# and it is called command line
argument.
• Main() method is where program stars execution. The main method doesn’t accept
parameter from any method. It accepts parameter through the command line. It is an array
type parameter that can accept n number of parameters at runtime.
STEPS
1. Open Notepad and write the following code and save it with anyname.cs
2. Open visual studio command prompt and compile the code as follow:
Set current path, where your program is saved.
Compile it with csc anyname.cs
3. Now execute the program using following command line argument:
anyname a1 a2
59. Inheritance
using System;
namespace Basic_Example
{
//Creating Base Class
class Tyre
{
protected void TyreType()
{
Console.WriteLine("This is Tubeless Tyre");
}
}
//Creating Child Class
class Scooter : Tyre
{
public void ScooterType()
{
Console.WriteLine("Scooter Color is Red");
TyreType();
}
}
//Creating Child Class
class Car : Tyre
{
public void CarType()
{
Console.WriteLine("Car Type : Ferrari");
TyreType();
}
}
class Program
{
static void Main(string[] args)
{
Scooter sc = new Scooter();
sc.ScooterType();
Car c = new Car();
c.CarType();
Console.ReadKey();
60. Inheritance And Constructors
//SEE NEXT PAGE
If base class has constructor then child class or derived class are
required to call the constructor from its base class.
class childclass : baseclass
{
public childclass()
{
}
public childclass(string message) : base(message)
{ }
}
61. In C#, both the base class and the derived class can
have their own constructor.
In inheritance, the derived class inherits all the
members(fields, methods) of the base class,
but derived class cannot inherit the constructor of
the base class because constructors are not the
members of the class.
Instead of inheriting constructors by the derived
class, it is only allowed to invoke the constructor of
base class.
62. Simple program for base class constructor
using System;
namespace Inheritance_Constructors
{
class baseclass
{
public baseclass()
{
Console.WriteLine("I am Default Constructors");
}
public baseclass(string message)
{
Console.WriteLine("Constructor Message : " + message);
}
}
class childclass : baseclass
{
public childclass(string message) : base(message)
{
}
}
class Program
{
static void Main(string[] args)
{
//childclass ch = new childclass();
childclass ch1 = new childclass("Hello Parent");
Console.ReadKey();
}
}
}