Structs - Video
Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"
Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No
Can you instantiate a struct without using a new operator in C#?
Yes, you can instantiate a struct without using a new operator
Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.
Can a struct inherit from an interface in C#?
Yes
Are structs value types or reference types?
Structs are value types.
What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.
Structure have default constructor which initialize the field member to zero.
ReplyDelete"No, a struct cannot inherit from another struct or class, and it cannot be the base of a class."
ReplyDelete"All structs inherit directly from System.ValueType, which inherits from System.Object."
Don't those two statements contradict one another?
System.ValueType does not derive from System.Object.
ReplyDelete// Summary:
// Provides the base class for value types.
[Serializable]
[ComVisible(true)]
public abstract class ValueType
{
// Summary:
// Initializes a new instance of the System.ValueType class.
protected ValueType();
// Summary:
// Indicates whether this instance and a specified object are equal.
//
// Parameters:
// obj:
// Another object to compare to.
//
// Returns:
// true if obj and this instance are the same type and represent the same value;
// otherwise, false.
public override bool Equals(object obj);
//
// Summary:
// Returns the hash code for this instance.
//
// Returns:
// A 32-bit signed integer that is the hash code for this instance.
public override int GetHashCode();
//
// Summary:
// Returns the fully qualified type name of this instance.
//
// Returns:
// A System.String containing a fully qualified type name.
public override string ToString();
}
}
I disagree. Everything derives from System.Object in C#. Even the value types.
DeleteYou don't see it in the definition because it is optional to have a class explicitly inhereting from System.Object.
why struct dont have destructor? Can any one explain me?
ReplyDeletebecoz struct is value type so dont need to destruct it
Delete