Structures
are like classes, where as we can create objects that behave like the built –in
types. They resemble most like classes even though it’s found lot of
differences between them.
Primitive
difference between them is
- Structures are value based where as classes are reference types
- Structures do not possess Deconstruct characteristics
- Inheritance is strictly not supported in structures where as in classes we do.
- Structures do not support OOPS concept
Example 1:
//
file: demo_42.cs
//Author:
SURESH BABU
//Purpose:
Structure definition
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo_42
{
//
Structure definition
struct Fraction
{
public int numerator;
public int denominator;
public void print()
{
Console.WriteLine(" {0} / {1}",
numerator, denominator);
}
}
class Program
{
static void Main(string[] args)
{
Fraction f;
f.numerator = 5;
f.denominator = 10;
f.print();
Fraction f2 = f;
f2.print();
//modify
struct instance f2
f2.numerator = 1;
f.print();
f2.print();
}
}
}
Example 2:
//File:
demo_43
//Author:
SURESH BABU
//Reference:
Defining a structure to as reference class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo_43
{
struct Rectangle
{
private int m_width;
public int width
{
get { return m_width; }
set { m_width = value; }
}
private int m_height;
public int height
{
get{return m_height;}
set {m_height=value;}
}
}
class Program
{
static void Main(string[] args)
{
int Area;
Area = 0;
Rectangle rect1 = new Rectangle();
Console.WriteLine("Enter
the value of widht and height of the Rectangle");
rect1.width = int.Parse(Console.ReadLine());
rect1.height = int.Parse(Console.ReadLine());
Console.WriteLine("Dimensions
of Width & Height");
Console.WriteLine("____________________");
Area = rect1.height * rect1.width;
Console.WriteLine("Width: {0}"+"cms"+"\nHeight: {1}"+"cms",
rect1.width, rect1.height);
Console.WriteLine("\nArea
of the Rectangle is {0}"+" sq.cms", Area);
}
}
}
No comments:
Post a Comment