.NET
  Home arrow .NET arrow Page 5 - .NET Type System, Part I
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
.NET

.NET Type System, Part I
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 44
    2005-03-08

    Table of Contents:
  • .NET Type System, Part I
  • The ILDASM.EXE Tool
  • System.Object Class
  • The Stack and the Heap
  • Structures: complex Value-Types
  • Enumerations

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    .NET Type System, Part I - Structures: complex Value-Types


    (Page 5 of 6 )

    The primitive data types such as int, double and byte represent simple values, but sometimes you need to store complex numerical values, such as a point on the screen in the form (x, y). Maybe you want to store the student English grade and French grade in one structure, and you may want to associate a number of operations with this structure. The primitive types can't help you to store such values, because you can't store two values in one variable. You may use a class in the following manner:

    public class StudentGrades
    {
      public int EnglishGrade = 40;
      public int FrenchGrade = 35;
    }

    But using a class (which is a Reference Type) to store two simple Value-Types (like x and y for the screen coordinates) would be very costly to the CLR. In C# we have another construction called a structure (defined using the keyword struct). When you need to define a Value-Type you will be defining structures. We can write the above class in the following structure:

    public struct StudentGrades
    {
      public int EnglishGrade = 40;
      public int FrenchGrade = 35;
    }

    You define a structure using the keyword struct, and you may precede it with an access modifier (the keyword public means that the structure is visible for any client code). Let's put the class StudentGrades and the structure StudentGradesStruct in one file and compile it so we can take a look at the MSIL. Copy the following code into a file and save it as StructClass.cs, then compile it using the command c:\csc /t:library StructClass.cs. Or you can use Visual Studio.NET to compile it as a Class Library by selecting a Class Library project.

    using System;
    namespace Structures
    {
      public class StudentGrades
      {
        public int EnglishGrade;
        public int FrenchGrade;
      } 

      public struct StudentGradesStruct
      {
        public int EnglishGrade;
        public int FrenchGrade;
      }
    }

    Now let's take a look at the MSIL code using the ILDASM tool. Write the following command:

    c:\ ildasm StructClass.dll

    The ILDASM tool will load the Class Library file StructClass.dll. Now double click on the namespace Structure and you will see both the class and the structure. Double click on both so you can see their members.

    You can learn a lot of "under the wood" concepts by loading your compiled files using this tool as we do here. Note the following points about both the class and the structure:

    • The class StudentGrades have a .ctor method, which is a default constructor, while the structure StudentGradesStruct has no constructor.

    • Both of them are just classes, but the class StudentGrades derive from System.Object, while the structure StudentGradesStruct derive from System.ValueType.

    • The structure is declared in the MSIL code as sealed, which means that it can't be a base class for other classes (it can't be inherited). 

    It's interesting, isn't it?

    Structures differ from Class in that they don't need the Garbage Collector (the .NET mechanism of destroying reference-Types) to reclaim the memory. Structures are Value-Types, which means that when you create a structure it will be located on the stack, and when the method completes, it will be destroyed. When you assign one structure instance to another, it will be copied much like the above assignment example.

    You should be careful when using structures because they're a Value-Type. What I mean is that, if you have a very large structure, then copying this structure in the application will slow down the performance. It's better to define that structure as a class because it's easier to copy a reference (classes exhibit Copy-By-reference behavior) of the class to another variable than to copy the values of the structure (say 20 int variable which means 80 bytes) to another one.

    Structures can contain fields, methods, indexers, events, constructors and properties, but can't contain destructors. This makes sense because they're not Heap-Based objects -- thus, they can't have destructors. There are some important points you should know about structures, because they are Stack-based objects.

    • You can't define a default constructor for a structure, because the CLR will define it and call it when you use the new operator to initialize the structure's fields to the default values, which are: false for Boolean Types, 0 for numerical Types.

    • You can't initialize a field in the same declaration statement, except for constant values, which you declare using the keyword const (if you are not familiar with constant values, we will talk about these in the article covering Class and Access Modifiers).

    • You can define as many parameterized constructors as you want to initialize your fields.

    • As we saw in the MSIL code, the Structure is declared using the keyword sealed, which means that you can't derive from it. In other words, it can't be a base class, so you will not use the C# keywords virtual, sealed or abstract. Note that when you define a structure it inherits from System.ValueType, and the C# compiler declares the class (the structure) as sealed, so you can't derive from it. You can inherit (implement) interfaces in a structure; this is a result of supporting methods in structures.

    • You can override the methods inherited from System.ValueType like the ToString() method to support your programming construction.

    Let's extend the StudentGradesStruct to override the inherited ToString() method. We will define two constructors to initialize the member fields.

    public struct StudentGradesStruct

      public int EnglishGrade;
      public int FrenchGrade;

      public StudentGradesStruct(int EG)
      {
        EnglishGrade = EG;
        FrenchGrade = 0;
      }

      public StudentGradesStruct(int EG, int FG)
      {
        EnglishGrade = EG;
        FrenchGrade = FG;
      }

      public override string ToString()
      {
        return Convert.ToString(EnglishGrade + FrenchGrade);
      }
    }

    There is nothing new about this code except for the ToString() method, which simply overrides the base class implementation (which returns the string System.ValueType) to return an appropriate representation of the data. In this case, we return the total grades. To run this code you need a test class like the following one:

    public class Test
    {
      static void Main()
      {
        StudentGradesStruct student = new StudentGradesStruct(40,35);
        Console.WriteLine(student.EnglishGrade.ToString());
        Console.WriteLine(student.FrenchGrade.ToString());
        Console.WriteLine(student.ToString());
        Console.ReadLine();
      }
    }

    You will get the following result from the console:

    40

    35

    70

    Note that you can call the ToString() method on any type in the .NET because it's an inherited functionality from the ultimate base class System.Object.

    Let's copy the student structure variable into another variable and see the result. Modify the Main method to look like the following:

    static void Main()
    {
      StudentGradesStruct student = new StudentGradesStruct(40,35);
      Console.WriteLine(student.EnglishGrade.ToString());
      Console.WriteLine(student.FrenchGrade.ToString());
      Console.WriteLine(student.ToString());

      //assignment statement
      StudentGradesStruct student2 = student;
      Console.WriteLine(student.EnglishGrade.ToString());
      Console.WriteLine(student.FrenchGrade.ToString());
      Console.WriteLine(student.ToString());

      Console.ReadLine();
    }

    The result would be:

    40

    35

    70

    40

    35

    70

    More .NET Articles
    More By Michael Youssef


     

    .NET ARTICLES

    - Using CrystalReportViewer to Display Crystal...
    - Creating Summary .Net Crystal Reports
    - More on Commands, Input and the WPF
    - Grouping and Aggregating When Querying LINQ ...
    - Commands, Input and the WPF
    - Keyboard and Ink Input with WPF
    - Mouse Input and the WPF
    - Input with Windows Presentation Foundation
    - Introducing LINQ with XML and Databases
    - An Introduction to LINQ
    - Querying LINQ to SQL: Basics
    - Completing a Simple Storefront with LINQ
    - Knowing Your Environment: the System.Environ...
    - Creating the Home Page for a Simple Storefro...
    - LINQ Quickly with Language Integrated Queries





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT