Custom Search

Monday, August 4, 2008

Defining methods in Structures (C#)

Normally you will see structures with only variables on it, but methods can also be included. This is usefull when you need to write a method that works directly with the content of the stuct.

- The first method that I will create inside the structure is a constructor. Remember that there can be many constructores as long as the parameter list is different of each other.
- The second method you will see next is a simple bool method that return true if both values of the structure varaibles (integers) are 50.

Ok, lets now proceed to write this example.

using System;

class Program

struct Point {

public int x;
public int y;

public Point(int x1, int y1) {

x = x1;
y = y1;

public bool check50() {

if ((x == 50) && (y == 50))
return true;

return false;



static void Main(string[] args)

Point p = new Point(50 , 50);
Point p2 = new Point(10, 20);

if (p.check50())
Console.WriteLine("Point p is at 50s");

Console.WriteLine("Point p not at 50s");

Console.WriteLine("Point p2 is at 50s");

Console.WriteLine("Point p2 not at 50s");


1 comment:

ankur said...

Your mathematical skills are quiet good.

Voucher Codes