Wednesday, December 08, 2004 - Posts

Sealed Classes, stucts and the C# Compiler

Check the code below.
What kinda of messages would the compiler produce. if any error would occur.?
 
//-------------------------------------------------------
struct MyStruct
{
 int MyInt;
}
 

sealed class MySealedClass
{
 
}
 
//Error : inherting from struct
class MyClass:MyStruct
{
 
}

//Error : inherting from sealed class
class MySealedChild:MySealedClass
{
 
}
//-------------------------------------------------------
 
 
incase your still wondering .. both produce CS0509.. check it out below.. funny how structs work just like as sealed classes but dont be misled they are value types
 
 
Compiler output
 
MyClass.cs(13,7): error CS0509: 'MyClass' : cannot inherit from sealed class 'MyStruct'
MyClass.cs(1,8): (Location of symbol related to previous error)
MyClass.cs(18,7): error CS0509: 'MySealedChild' : cannot inherit from sealed class 'MySealedClass'
MyClass.cs(7,14): (Location of symbol related to previous error)
 
 
with 0 Comments

MSIL - .class and why not .struct

Even wondered how the struct got compiled to IL, if you have and didnt know then check this out. It comes using a  .class and somehow makes the impression that its a struct. For c++ guys i still wonder where this definition of stuct would fit in. Yes i have to make a note that its a value type and there ends the difference, dont know if im missing out on something here

//Struct declaration
struct MyStruct
{
 int MyInt;
}

//Generated partial MSIL
.class private sequential ansi sealed beforefieldinit MyStruct
           extends
[mscorlib]System.ValueType
{
      
.field private int32
MyInt
}

I havent yet checked on all words inside the IL spec.. so do let me know if you have any feed back on this.

with 0 Comments