SIGN UP MEMBER LOGIN:    
Resource

Structs in C#

XAML Designer Resources Oct 05, 2009
Structs,struct,structure,C#,Csharp, c-sharp

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color.

public struct CoOrds
{
public int x, y;

public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
Here are two examples of how to create and use structs.

Example 1.

This example demonstrates struct initialization using both default and parameterized constructors.

Here is structure definition:
public struct CoOrds
{
public int x, y;

public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
This is how you use the struct defined earlier.
// Declare and initialize struct objects.
class TestCoOrds
{
static void Main()
{
// Initialize:
CoOrds coords1 = new CoOrds();
CoOrds coords2 = new CoOrds(10, 10);

// Display results:
Console.Write("CoOrds 1: ");
Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

Console.Write("CoOrds 2: ");
Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y);

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
CoOrds 1: x = 0, y = 0
CoOrds 2: x = 10, y = 10
*/

Example 2

This example demonstrates a feature that is unique to structs. It creates a CoOrds object without using the new operator. If you replace the word struct with the word class, the program will not compile.

Here is the struct definition.
public struct CoOrds
{
public int x, y;

public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
This is how you use the struct defined earlier.
// Declare a struct object without "new."
class TestCoOrdsNoNew
{
static void Main()
{
// Declare an object:
CoOrds coords1;

// Initialize:
coords1.x = 10;
coords1.y = 20;

// Display results:
Console.Write("CoOrds 1: ");
Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: CoOrds 1: x = 10, y = 20
share this resource :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Sponsored by
Nevron Gauge for SharePoint
Become a Sponsor