GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

GeekInterview.com  >  Interview Questions  >  Microsoft  >  C#
Go To First  |  Previous Question  |  Next Question 
 C#  |  Question 36 of 431    Print  

What is the difference between a struct and a class in C#?

From language spec:

The list of similarities between classes and structs is as follows.

Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather

than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.


  
Total Answers and Comments: 2 Last Update: December 07, 2005   
  
 Sponsored Links

 
 Best Rated Answer
Submitted by: samiksc
 

Following are the main points of difference between classes and structs in C#:

  1. Value type vs Reference type: Structs are value type and classes are reference type.
    • Whenever a struct object is assigned to another struct object a copy is created. In case of classes the same operation results in two references referring to same object: For example, a.x = 10; b = a; a.x = 20; cout << b.x will display '10' if a and b are struct objects and it will display '20' if a and b are class objects.
    • Boxing of a struct object creates a copy of the object in a different type, whereas, boxing a class object creates a reference (of different type) to the same object.
    • Since structs are value type it is not possible to assign null to a struct object.
    • When a struct object is passed to a function as a parameter it is passed by value, unless specifically marked as 'ref' or 'out' parameter.
  2. Inheritance: Inheritance is not allowed for structs.
    • All struct types implicitly inherit from System.ValueType and they are implicitly sealed.
    • The keywords related to inheritance concepts are not allowed for structs. For example, abstract, protected, virtual, override etc.
  3. Initialization: Structs cannot have default constructor.
    • All struct member variables of value type are initialized to their default values and reference member variables are initialized to null.
    • Field initializers (initialization in the member variable declaration line like int a = 0; ) is also not allowed for structs.
  4. Destructor: Structs cannot declare a destructor.
  5. Meaning of 'this':
    • For a struct instance constructor (parameterized) 'this' is treated as an out parameter.
    • For other member functions it is treated as a 'ref' parameter.
    • So it is possible to assign to 'this' and change the current object.
    • In case of a class 'this' is considered as a value, so it is not possible to assign to 'this' from inside a class.
    • Since 'this' is a 'ref' or 'out' parameter, it must be definitely assigned at every point where it is used.


Above answer was rated as good by the following members:
Nageswara Rao.Garine
December 07, 2005 01:56:00   #1  
samiksc Member Since: October 2005   Contribution: 233    

RE: What is ...

Following are the main points of difference between classes and structs in C#:

  1. Structs are value type and classes are reference type.
    • Whenever a struct object is assigned to another struct object a copy is created. In case of classes the same operation results in two references referring to same object: For example, a.x = 10; b = a; a.x = 20; cout << b.x will display '10' if a and b are struct objects and it will display '20' if a and b are class objects.
    • Boxing of a struct object creates a copy of the object in a different type, whereas, boxing a class object creates a reference (of different type) to the same object.
  2. Inheritance is

 
Is this answer useful? Yes | No
December 07, 2005 02:10:37   #2  
samiksc Member Since: October 2005   Contribution: 233    

RE: What is ...

Following are the main points of difference between classes and structs in C#:

  1. Value type vs Reference type: Structs are value type and classes are reference type.
    • Whenever a struct object is assigned to another struct object a copy is created. In case of classes the same operation results in two references referring to same object: For example, a.x = 10; b = a; a.x = 20; cout << b.x will display '10' if a and b are struct objects and it will display '20' if a and b are class objects.
    • Boxing of a struct object creates a copy of the object in a different type, whereas, boxing a class object creates a reference (of different type) to the same object.
    • Since structs are value type it is not possible to assign null to a struct object.
    • When a struct object is passed to a function as a parameter it is passed by value, unless specifically marked as 'ref' or 'out' parameter.
  2. Inheritance: Inheritance is not allowed for structs.
    • All struct types implicitly inherit from System.ValueType and they are implicitly sealed.
    • The keywords related to inheritance concepts are not allowed for structs. For example, abstract, protected, virtual, override etc.
  3. Initialization: Structs cannot have default constructor.
    • All struct member variables of value type are initialized to their default values and reference member variables are initialized to null.
    • Field initializers (initialization in the member variable declaration line like int a = 0; ) is also not allowed for structs.
  4. Destructor: Structs cannot declare a destructor.
  5. Meaning of 'this':
    • For a struct instance constructor (parameterized) 'this' is treated as an out parameter.
    • For other member functions it is treated as a 'ref' parameter.
    • So it is possible to assign to 'this' and change the current object.
    • In case of a class 'this' is considered as a value, so it is not possible to assign to 'this' from inside a class.
    • Since 'this' is a 'ref' or 'out' parameter, it must be definitely assigned at every point where it is used.

 
Is this answer useful? Yes | NoAnswer is useful 1   Answer is not useful 0Overall Rating: +1    

 Related Questions

All methods marked with the DllImport attribute must be marked as public static extern.  
Latest Answer : It works perfectly.  You can find the dialogue window by using "ALT+Tab" keyRobert  ...

C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#: switch(x){case 0:// do somethingcase 1:// do something in common with 0default:// 
Latest Answer : c# switch allows fall through if and only if in empty case. as long as there is a statement in the case it must  use break or go to to  jump out of the case. ...

The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case 
Latest Answer : Constant : The constants are the one whose value remain same at all the time.it will be used if u want to define something at compile time.Read only....if you don't know value at compile time but u can find that at runtime that time u can use ...

Use a conditional attribute on the method, as shown below: class Debug{[conditional("TRACE")]public void Trace(string s){Console.WriteLine(s);}}class MyClass{public static void Main(){Debug.Trace("hello");}}In 
Latest Answer : if you are using conditinoal attribute then add the name spaceSystem.Diagnostics.ConditionalAttribute ...

You need to use the /target:library compiler option.  
Latest Answer : Open the property page of the Project File and thenopen CommonProperties -> Genaral ->Output Typechange the output type to class library and build the application then u'll get a dll file.also in the Configuartion Properties ->Build -> Output ...

The word checked is a keyword in C#.  
Latest Answer : Reason is checked is a keyword in C#,but if u want to keyword as an identifier use @ with it.e.g int @checked=3;This works with all the keywords,but it is recommended to avoid it. ...

What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
The syntax for calling another constructor is as follows: class B{B(int i){ }}class C : B{C() : base(5) // call base constructor B(5){ }C(int i) : this() // call C(){ }public static void Main() {}}  

C# has the is operator: expr is type  
Latest Answer : EX:==============using System; class ClassA {} public class TestIs{   public static void Test (object o)    {      ClassA a = null;       if (o is ClassA)       ...

If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following 
Latest Answer : If your method does not have any return type then mention void before that method or return 0 ...

Strings are not null terminated in the runtime, so embedded nulls are allowed. Console.WriteLine() and all similar methods continue until the end of the string.  
Latest Answer : Console.WriteLine() stop printing when it reaches a 'Carriage Return' (denotes next line) character within a string! ...


 Sponsored Links

 
Related Articles

C++ Pure Virtual Function and Base Class

C Pure Virtual Function and Virtual Base Class In this C tutorial you will learn about pure virtual function declaration of pure virtual function and virtual base class virtual base class and how to implement a virtual base class explained with examples mosgoogle center What is Pure Virtual Function
 

How to Access C++ Class Members

How to Access C Class Members In this C tutorial you will learn how to access Class members dot operator or class member access operator difference between struct and class and&nbsp; scope resolution operator mosgoogle center It is possible to access the class members after a class is defined an
 

What is difference between call by value and call by reference in function?

The arguments passed to function can be of two types 1. Values passed 2. Address passed The first type refers to call by value and the second type refers to call by reference. For instance consider program1 main() { int x=50, y=70; interchange(x,y); printf(&ldquo;x=%d y=%d&rdquo;,x,
 

The Interview Snafu

How to turn someone else&rsquo;s mistake to your advantage Your dream job is about to become reality. A recruiter gave you the heads up about the perfect position at Humungous Conglomerate, Inc. You went through five interviews as well as a battery of psychological tests mandated by their HR de
 

Winning a Job Interview with a Winning Resume

Does your resume unlock your potential, take your skills to the highest level and win you the interview and the job you want now? The job market today is highly competitive and even if you think you have what it takes to get an interview you won&rsquo;t get over the line without a polished, prof
 

UML Elements : Class Diagram

UML Elements UML 2 0 is comprised of a total of 13 diagrams If you wish to understand these diagrams they should be organized based on a hierarchy For UML a diagram is an element which must define which things should be modeled in a system mosgoogle center Introduction to Class Diagram In this arti
 

Importance of Proper English during Job Interview

Importance of Proper English during Job Interview Your job interview is crucially important and it will determine whether or not you will get the job Depending on the type of job you re going for it is very important for you to use proper English In most cases jobs which offer higher salaries will h
 

Difference between Scholarship and Grant

Difference between Scholarship and Grant While both scholarships and grants allow students to pay for their tuition without having to pay the money back there are a number of key differences between the two Knowing the difference between grants and scholarship will make it much easier for students t
 

HR Interview - HR Interview Mistakes You Will Want To Avoid

HR Interview Mistakes You Will Want To Avoid The job interview can be a stressful process This is especially true for those who are going after a competitive position Your nonverbal communication combined with the answers you give during the interview will determine if you are hired mosgoogle While
 

HR Interview - Behavioral HR Interviews

Behavioral HR Interviews As the name implies a behavioral interview is an interview that is held by a human resources department to determine if an applicant has the behaviors that are appropriate for a job The company must know how an applicant will behave in a certain situations mosgoogle The logi
 





About Us  |   Privacy Policy  |   Terms and Conditions  |   Contact  |   Site Map  |   Add Question  |   Propose Category  |   RSS Feeds  |   Articles Sitemap  |   Site Updates  |   Add Resource

Copyright © 2005 - 2008 GeekInterview.com. All Rights Reserved
Page copy protected against web site content infringement by Copyscape