Structs

Structs is value-type user defined data type same as int, float, bool etc.

Structs features:


* structs are value-type

* In structs memory allocation can be done on stack.

* No garbage collector required to remove structs variable because as they are value type, the memory allocated is on stack and so no memory allocated on heap, when structs variable are not in used they just fall from the stack.

* Structs can't have destructors.

* Structs can't inherit another class or structs. This means there is no concept of inheritance in structs.

* Structs may inherit multiple interfaces. Interface is a reference type and any class or structs that implements interface must override all the methods that are there in the interface.



ClsStruct11.cs


using System;
using System.Collections.Generic;
using System.Text;

namespace cSHARPEXAMPLES
{
interface ITest
{
string Test();
}

struct Rectangle : ITest
{
public int length;
public int breath;
public int height;

public Rectangle( int length, int breath, int height)
{
this .length = length;
this .breath = breath;
this .height = height;
}

public Rectangle Add( Rectangle rect)
{
Rectangle newRect;
newRect.length = length + rect.length;
newRect.breath = breath + rect.breath;
newRect.height = height + rect.height;
return newRect;
}

public string Test()
{
return "Implements Interface in structs" ;
}
}

class ClsStruct11
{
public String display()
{
Rectangle rect1 = new Rectangle (10, 20, 30);
Rectangle rect2 = new Rectangle (110, 120, 130);
Rectangle rect3;
rect3 = rect1.Add(rect2);
return "Length :: " + rect3.length + "\n Breadth :: " + rect3.breath + "\n Height :: " + rect3.height;
}
public string print()
{
Rectangle rect1 = new Rectangle (10, 20, 30);
return rect1.Test();
}
}
}


Form11.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace cSHARPEXAMPLES
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)
{ // Structs Implementation
label1.Text = "" ;
ClsStruct11 obj = new ClsStruct11 ();
label1.Text = obj.display();
}

private void button2_Click( object sender, EventArgs e)
{ // Structs Implementing Interface
label2.Text = "" ;
ClsStruct11 obj = new ClsStruct11 ();
label2.Text = obj.print();
}
}
}


Comments

Author: Mrs. Meetu Choudhary Nanda21 Feb 2009 Member Level: Gold   Points : 0

Hi.
Nice Article..
Keep It UP.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: