Object Oriented Concepts C#
object-oriented-concepts-c-sharp
object-oriented-concepts-c-sharp
Partial class with partial method declaration:
partial class MyPartialClass { ... partial void ValidateInput(decimal amount); }
Partial class with partial method body:
partial class MyPartialClass { ... partial void ValidateInput(decimal amount) { if (amount> 100) throw new ArgumentException ("Too Big"); } }
Order class:
public class Order { public int OrderID; public string CustomerID; public int EmployeeID; public DateTime OrderDate; public DateTime RequiredDate; public DateTime ShippedDate; public int ShipVia; public decimal Freight; public string ShipName; public string ShipCity; public string ShipRegion; public string ShipCountry; public List <Order_Detail> Order_Details; public Customer Customer; public Employee Employee; public Shipper Shipper; }
Function to create order list:
public List <Order> CreateOrderList() { List <Order> OrderList = new List <Order> { new Order {OrderID = 10248, CustomerID = “TATA”, EmployeeID = 5, OrderDate = DateTime.Parse(“7/4/1996”, CultureInfo.CreateSpecificCulture(“en-US”))), RequiredDate = DateTime.Parse(“8/1/1996”, CultureInfo.CreateSpecificCulture(“en-US”))), ShippedDate = DateTime.Parse(“7/16/1996”, CultureInfo.CreateSpecificCulture(“en-US”))), ShipVia = 3, Freight = 32.3800M, ShipName = “DHL USA”, ShipCountry = “Bangladesh”, Order_Details = new List <Order_Detail> (), Customer = new Customer(), Employee = new Employee(), Shipper = new Shipper()}, new Order {OrderID = 10249, CustomerID = “BIRLA”, EmployeeID = 6, OrderDate = DateTime.Parse(“7/5/1996, CultureInfo.CreateSpecificCulture(“en-US”))”), RequiredDate = DateTime.Parse(“8/16/1996, CultureInfo.CreateSpecificCulture(“en-US”))”), ShippedDate = DateTime.Parse(“7/10/1996”, CultureInfo.CreateSpecificCulture(“en-US”))), ShipVia = 1, Freight = 11.6100M, ShipName = “DHL USA”, ShipCountry = “India”, Order_Details = new List <Order_Detail> (), Customer = new Customer(), Employee = new Employee(), Shipper = new Shipper()} }; return OrderList; }
The class:
using System; public class Movie { public string Title { get; set; } public string Director { get; set; } public int Genre { get; set; } public int RunTime { get; set; } public DateTime ReleaseDate { get; set; } }
<script runat="server"> protected void Page_Load(object sender, EventArgs e) { var movies = GetMovies(); this.GridView1.DataSource = movies; this.GridView1.DataBind(); } public List<Movie> GetMovies() { return new List<Movie> { new Movie { Title="Shrek", Director="Andrew Adamson", Genre=0, ReleaseDate=DateTime.Parse("5/16/2001"), RunTime=89 }, new Movie { Title="Fletch", Director="Michael Ritchie", Genre=0, ReleaseDate=DateTime.Parse("5/31/1985"), RunTime=96 }, new Movie { Title="Casablanca", Director="Michael Curtiz", Genre=1, ReleaseDate=DateTime.Parse("1/1/1942"), RunTime=102 } }; } </script>
To handle an event you need to subscribe to it by providing an event handler method whose return type and parameters match that of the delegate specified for use with the event. The following example uses a simple timer object to raise events, which results in a handler method being called.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace w3m { class Program { static int counter = 0; static string displayString = "This string will appear one letter at a time. "; static void Main(string[] args) { Timer myTimer = new Timer(100); myTimer.Elapsed += WriteChar; myTimer.Start(); Console.ReadKey(); } static void WriteChar(object source, ElapsedEventArgs e) { Console.Write(displayString[counter++ % displayString.Length]); } } }
The .NET Framework provides the infrastructure to serialize objects in the System.Runtime.Serialization and System.Runtime.Serialization.Formatters namespaces.
System.Runtime.Serialization.Formatters.Binary—This namespace contains the class BinaryFormatter, which is capable of serializing objects into binary data, and vice versa.
System.Runtime.Serialization.Formatters.Soap— This namespace contains the class SoapFormatter, which is capable of serializing objects into SOAP format XML data, and vice versa.
Serializing using BinaryFormatter is as simple as this:
IFormatter serializer = new BinaryFormatter(); serializer.Serialize(myStream, myObject);
Deserializing is equally easy:
IFormatter serializer = new BinaryFormatter(); MyObjectType myNewObject = serializer.Deserialize(myStream) as MyObjectType;
Example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace ObjectStore { class Program { static void Main(string[] args) { try { // Create products. List<Product> products = new List<Product>(); products.Add(new Product(1, "Spiky Pung", 1000.0, "Good stuff.")); products.Add(new Product(2, "Gloop Galloop Soup", 25.0, "Tasty.")); products.Add(new Product(4, "Hat Sauce", 12.0, "One for the kids.")); Console.WriteLine("Products to save:"); foreach (Product product in products) { Console.WriteLine(product); } Console.WriteLine(); // Get serializer. IFormatter serializer = new BinaryFormatter(); // Serialize products. FileStream saveFile = new FileStream("Products.bin", FileMode.Create, FileAccess.Write); serializer.Serialize(saveFile, products); saveFile.Close(); // Deserialize products. FileStream loadFile = new FileStream("Products.bin", FileMode.Open, FileAccess.Read); List<Product> savedProducts = serializer.Deserialize(loadFile) as List<Product>; loadFile.Close(); Console.WriteLine("Products loaded:"); foreach (Product product in savedProducts) { Console.WriteLine(product); } } catch (SerializationException e) { Console.WriteLine("A serialization exception has been thrown!"); Console.WriteLine(e.Message); } catch (IOException e) { Console.WriteLine("An IO exception has been thrown!"); Console.WriteLine(e.ToString()); } Console.ReadKey(); } } }
Product class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ObjectStore { [Serializable] public class Product { public long Id; public string Name; public double Price; [NonSerialized] string Notes; public Product(long id, string name, double price, string notes) { Id = id; Name = name; Price = price; Notes = notes; } public override string ToString() { return string.Format("{0}: {1} (${2:F2}) {3}", Id, Name, Price, Notes); } } }
To declare a dynamically sized array of objects of a specific type we can use a generic list List
class Person { public string Name { get; set; } public string Address { get; set; } } static void Main(string[] args) { List<Person> people = new List<Person>(); people.Add(new Person() { Name = "kaka", Address = "22,2nd cross,bangalore" }); //no casting needed Person p = people[0]; }
By default, ToString() will display the type’s name. To show your own values, you must override the ToString() method.
struct My3d { private double _x; private double _y; private double _z; public double X { get { return _x; } set { _x = value; } } public double Y { get { return _y; } set { _y = value; } } public double Z { get { return _z; } set { _z = value; } } public My3d(double x, double y, double z) { this._x = x; this._y = y; this._z = z; } public override string ToString() { return string.Format("({0}, {1}, {2})", X, Y, Z); } }
Instantiate the class as follows:
My3d v = new My3d(1.0, 2.0, 3.0); Trace.WriteLine(v.ToString());
Output:
(1, 2, 3)
C# uses the interface statement along with opening and closing braces to indicate the beginning and end of an interface definition. For example:
public interface IDataAdapter { // Member definitions }
In VB, an interface definition is indicated by the Interface… End Interface construct:
Public Interface IDataAdapter ' member definitions End Interface
C# uses the colon with interfaces to specify any implemented interfaces. For example:
public interface IDataReader : IDisposable, IDataRecord
In VB, any implemented interfaces are specified by an Implements statement on the line immediately following the Interface statement. The previous definition of IDataReader in C# would appear as follows in VB:
Public Interface IDataReader Implements IDisposable, IDataRecord
C# uses the struct statement along with opening and closing braces to indicate the beginning and end of a structure definition.
Example defined in C#:
public struct SomeStruct { // Member definitions }
In VB, a structure definition is indicated by the Structure… End Structure construct:
Public Structure SomeStruct ' member definitions End Structure
C#
Equivalent VB keyword
C# uses the colon to indicate either inheritance or interface implementation. Both the base class and the implemented interfaces are part of the class statement.
Example:
public class DataSet : MarshalByValueComponent, IListSource, ISupportInitialize, ISerializable
In VB, the base class and any implemented interfaces are specified on separate lines immediately following the Class statement. A class’s base class is indicated by preceding its name with the Inherits keyword; any implemented interfaces are indicated by the Implements keyword.
Example in VB:
Public Class DataSet Inherits MarshalByValueComponent Implements IListSource, ISupportInitalize, ISerializable
C# uses the class statement along with opening and closing braces, { }, to indicate the beginning and end of a class definition.
For example:
public class DataException : SystemException { // Member definitions }
In VB, a class definition is indicated by the Class… End Class construct:
Public Class DataException Inherits SystemException ' member definitions End Class
C# classes can be marked as abstract or sealed; these correspond to the VB MustInherit and NonInheritable keywords
Private constructor are very important feature used extensively in Object oriented design and development. They are used when you don’t want to instantiate class and at the same time use its members. They are used when class only has static members.
Class Calculator { public static double e = 2.71828; private Calculator() { } public static int Add (int a,int b) { return a + b ; } Public static int Subtract (int a,int b) { Return a - b ; } Public static int Multiply(int a,int b) { return a * b ; } }
We cannot create objects of the “Calculator” as the constructor is private and even if we don’t specify access modifier it is treated as private.Such classes are used when you have lot of utility to be shared
in the application and don’t want to waste memory by creating objects every time you want to use such utility class.In that case you create all utility methods(or variables) as static members in class containing private constructor.
Following are the differences between structure and classes
1. Structures are value type and Classes are reference type.
2. Structures can not have constructor or destructor. Classes can have both constructor and destructor.
3. Structures do not support Inheritance, while Classes support Inheritance
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// A base class reference can refer to a derived class object. using System; class X { public int a; public X(int i) { a = i; } } class Y : X { public int b; public Y(int i, int j) : base(j) { b = i; } } public class BaseRef { public static void Main() { X x = new X(10); X x2; Y y = new Y(5, 6); x2 = x; // OK, both of same type Console.WriteLine("x2.a: " + x2.a); x2 = y; // still Ok because Y is derived from X Console.WriteLine("x2.a: " + x2.a); // X references know only about X members x2.a = 19; // OK // x2.b = 27; // Error, X doesn't have a b member } }
using System;abstract public class MotorVehicle { public string make; public string model; public MotorVehicle(string make, string model) { this.make = make; this.model = model; } abstract public void Accelerate();}public class Product : MotorVehicle { public Product(string make, string model) : base(make, model) { // do nothing } public override void Accelerate() { Console.WriteLine("In Product Accelerate() method"); Console.WriteLine(model + " accelerating"); } }class MainClass { public static void Main() { Product myProduct = new Product("Toyota", "MR2"); myProduct.Accelerate(); } }
/* C# Programming Tips & Techniques by Charles Wright, Kris JamsaPublisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // // Property.cs -- Demonstrates access to a private field through a property. // Compile this program with the following command line: // C:>csc Property.cs // namespace nsProperty { using System; public class Property { const double radian = 57.29578; const double pi = 3.14159; int Angle { get { int angle = (int) (fAngle * radian + 0.5); angle = angle == 360 ? 0 : angle; return (angle); } set { double angle = (double) value / radian; if (angle < (2 * pi)) { fAngle = angle; Console.WriteLine ("fAngle set to {0,0:F5}", fAngle); } else { Console.WriteLine ("fAngle not modified"); } } } double fAngle = 0.0; // Angle in radians static public int Main (string [] args) { int angle; try { angle = int.Parse (args[0]); } catch (IndexOutOfRangeException) { Console.WriteLine ("usage: circle [angle in degrees]"); return (-1); } catch (FormatException) { Console.WriteLine ("Please use a number value for the angle in degrees"); return (-1); } Property main = new Property(); main.Angle = angle; Console.WriteLine ("The angle is {0} degrees", main.Angle); return (0); } } }
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Add a constructor to Building. using System; class Building { public int floors; // number of floors public int area; // total square footage of building public int occupants; // number of occupants public Building(int f, int a, int o) { floors = f; area = a; occupants = o; } // Display the area per person. public int areaPerPerson() { return area / occupants; } /* Return the maximum number of occupants if each is to have at least the specified minum area. */ public int maxOccupant(int minArea) { return area / minArea; } } // Use the parameterized Building constructor. public class BuildingDemo21 { public static void Main() { Building house = new Building(2, 2500, 4); Building office = new Building(3, 4200, 25); Console.WriteLine("Maximum occupants for house if each has " + 300 + " square feet: " + house.maxOccupant(300)); Console.WriteLine("Maximum occupants for office if each has " + 300 + " square feet: " + office.maxOccupant(300)); } }
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */// Add a constructor to Triangle. using System; // A class for two-dimensional objects. class TwoDShape { double pri_width; // private double pri_height; // private // properties for width and height. public double width { get { return pri_width; } set { pri_width = value; } } public double height { get { return pri_height; } set { pri_height = value; } } public void showDim() { Console.WriteLine("Width and height are " + width + " and " + height); } } // A derived class of TwoDShape for triangles. class Triangle : TwoDShape { string style; // private // Constructor public Triangle(string s, double w, double h) { width = w; // init the base class height = h; // init the base class style = s; // init the derived class } // Return area of triangle. public double area() { return width * height / 2; } // Display a triangle's style. public void showStyle() { Console.WriteLine("Triangle is " + style); } } public class Shapes3 { public static void Main() { Triangle t1 = new Triangle("isosceles", 4.0, 4.0); Triangle t2 = new Triangle("right", 8.0, 12.0); Console.WriteLine("Info for t1: "); t1.showStyle(); t1.showDim(); Console.WriteLine("Area is " + t1.area()); Console.WriteLine(); Console.WriteLine("Info for t2: "); t2.showStyle(); t2.showDim(); Console.WriteLine("Area is " + t2.area()); } }
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Add a method that takes two arguments. using System; class ChkNum { // Return true if x is prime. public bool isPrime(int x) { for(int i=2; i < x/2 + 1; i++) if((x %i) == 0) return false; return true; } // Return the least common denominator. public int lcd(int a, int b) { int max; if(isPrime(a) | isPrime(b)) return 1; max = a < b ? a : b; for(int i=2; i < max/2 + 1; i++) if(((a%i) == 0) & ((b%i) == 0)) return i; return 1; } } public class ParmDemo1 { public static void Main() { ChkNum ob = new ChkNum(); int a, b; for(int i=1; i < 10; i++) if(ob.isPrime(i)) Console.WriteLine(i + " is prime."); else Console.WriteLine(i + " is not prime."); a = 7; b = 8; Console.WriteLine("Least common denominator for " + a + " and " + b + " is " + ob.lcd(a, b)); a = 100; b = 8; Console.WriteLine("Least common denominator for " + a + " and " + b + " is " + ob.lcd(a, b)); a = 100; b = 75; Console.WriteLine("Least common denominator for " + a + " and " + b + " is " + ob.lcd(a, b)); } }