We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Tuesday, July 28, 2015

Interview questions and answers of strutcture in C#

1. What is structure in C#?
A structure is a user defined data type that can contain different members as a variable, Method , properties, etc. Structures are value types and stored on the stack memory.

2. What is the advantage of structure in C#?

  • Structures are stored on the stack, so there is some advantage of structures.
  • Structure is created more quickly than heap-allocated.
  • Structures are automatically deallocated ,when it go the out of the scope.
  • Structures are value types so that we can easily copy value type variables on the stack memory.
3. How does define structure in C#?
Syntax:-
structstructure_name
{
data-member 1;
data-member 2;
data-member 3;
.
.
.
}
Ex:-
struct Employee
{
public string Name;
public int e-id;
public money salary;
}
Employee e1;

4. How does assign the values in structure's member in C#?
e1. Name = 'Ram';
e1. e-id = 101;
e1. salary = 2000;

5. How does copy values from one structure to another structure in C#?
When we create an object of any structured class, the data member of that structure automatic comes in memory. So if we want to copy values from one structure to another structure then we have to assign the one structure's object to another structure's object. Which is given below:
Ex.
Employee e1 ;
Employee e2 ;
e1 = e2; (structure second copied to first structure)

6. Does Structure members private by default in C#?
Yes, Structure members are private by default in C#. We can not access private member from the outside using dot operators.

7. How can we use constructor and method in a C# program?

class Program
        {
            struct rectangle
            {
                int x,y;
public rectangle(int a, int b) //Constructor
                {
                    x = a;
                    y = b;
                }
                public void Area() // method
                {
                    Console.WriteLine("area of rectangle is: ");
                    Console.WriteLine(x * y);
                }
            }
            static void Main(string[] args)
            {
                rectangle rect = new rectangle(20, 30);
                rect.Area();
                Console.ReadLine();
            }       
    }

output
area of rectangle is: 600

8. Can we use Nested Structures in C#?
Yes.
struct salary
{
char name [20];
char department[10];
struct
{
int dearness;
inthous_rent;
int city;
}
allowance;
}
employee;

9. What is the difference between Structure and Class in C#?
Difference between Structure and class :

  • The structure is stored within stack memory and Class is stored within heap memory.
  • In Structure we can not define parameter less constructor but in class can do it.
  • In structure we can not initialize the data member at declaration but in class can do it. 
  • In structure inheritance is not possible(one structure can not be inherited to another structure )but in class it is possible.
  • We can not declare virtual override and abstract keyword with structure but in class it is possible.
  • Class is a Reference type but the structure is a value type.
  • We can use Destructor in Class but not in Structure.

10. Does C# support parameterless constructor for structure by default?
No, C# does not support parameter less constructor.

11. What is Enumeration in C#?
An Enumeration is a user-defined integer type, which is used for attaching names to Numbers. We use enumkeyword for Enumeration in C#.

12. What is the Syntax Enumeration in C#?

Syntax:-
enum {value 1,value 2,value 3, ........value n}
Ex.
enum Days {mon,tue,wed,thu,fri,sat,sun}

13. What is the value of the first enum member by default in C#?
Zero(0)

14. How does assign values in enum member manually in C# ?
enum color
{
white =1;
red=2;
blue=3;
green=4;
}

15. What is the type of an enum by default in C#?

int

16. How can we declare explicitly a base type for each enum in C#?
The valid base types are:-
byte, sbyte, short, ushort, int ,uint , long , ulong
Ex.
enum shape : long
{
rectangle ;
square ;
triangle =100;
circle;
}

Note:-The value assigned to the members must be within the range of values that can be represented by the base type in C#, Means we can assign value in enum members within range of the base type.

17. What is type conversion in Enumeration in C#?
enum type can be converted to their base type.we can use explicit conversion to convert back using Cast function.
Ex.
enum number
{
value 0,
value 1,
value 2,
}
number n = (number) 1;
int x = int (int)n;
.................................

Note:- Literal values can be converted to an enum type without anycast.

18. Can we use Implicit and Explicit conversion in Enumerator?
Yes.

19. When do we prefer the use of structs over the class?
We do not prefer structure if it satisfied the following statement which is given below:

  • For represent a single value.
  • size is smaller than 16 bytes
  • immutable
  • for boxing 
20. What is the purpose of a constructor in a Structure?
Constructors are basically used for the initialization of the data members in the structure.


21. Why structs cannot have destructors?
Becuase by definition destructors are used to destruct instances of classes, and structs are value types. Destructor (Finalize) in C# is called implicitly from GC. It is used to free up the memory allocated in Heap. Reference type objects are stored in Heap. GC allocates and deallocates memory for only reference type and uses heap. But structures are value type so there is no need to have a destructor.

22. Default Access modifiers of Structure and enum in C# ?An enum has default modifier as public

A struct has default modifier as Internal and it can declare its members (methods etc) with following access modifiers:
  • public
  • internal
  • private
23. Why can't you declare a static struct in C#, but they can have static methods?
The CLR doesn't have any way to prevent an instance of a struct type from being created. Even if there is no public default constructor, simply declaringstruct S { }

S[] items = new S[]{1};

would create an instance of the struct with all of the associated memory set to zero bits.

This is different from a reference type (class) where the same code would create a reference of the specified type (referencing no object aka null) but not an instance of the object itself.

24. What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.

25. Explain the similarities between class and struct?
Structures and classes are similar in the following respects:

  • Both are container types, meaning that they contain other types as members.
  • Both have members, which can include constructors, methods, properties, fields, constants, enumerations, events, and event handlers. However, do not confuse these members with the declared elements of a structure.
  • Members of both can have individualized access levels. For example, one member can be declared Public and another Private.
  • Both can implement interfaces.
  • Both can have shared constructors, with or without parameters.
  • Both can expose a default property, provided that property takes at least one parameter.
26. Difference between structure and Enum?
Enum Structure

Collecton of disticnct named constant It can store multiple related data with different datatype

It contains fixed values It is a way to store data

27.)What are the predefined methods in Enums?
  • ConsoleColor
  • DayOfWeek
  • PlotFormID
  • TypeCode
28. NameSpaceHierachy for enums
  • Systm.object
  • System.ValueType
  • System.Enum
29. What is the HasFlag method?
Determines whether one or more bit fields are set in the current instance.

30. Following are some formations of the Format method
Format
Description

"G" or "g"
If the value is equal to a named enumerated constant, the name of that constant is returned; otherwise, the decimal equivalent of value is returned.

"X" or "x"

Represents value in a hexadecimal format without a leading "0x".

"D" or "d"

Represents value in decimal form.

31. What are the advantages of Enums?

  • Code becomes more readable.
  • Makes it easy to change values in the future.
  • enumerater not allocated in memory. They exist only on the compilation stage. When code runs

32. Classes and structs can be declared as static, Is this statement true or false?
False, only classes can be declared as static and not structs

33. How to return a structure using a function in C#?

hello
check out the code
public object FunctioName()
{
return structureObject
}

call this function
create a structure object first
SampleStructobj = new SampleStruct();
obj = (SampleStruct) FunctioName();

35. Differences between structures and arrays?

  • Array elements are homogeneous. Structure elements are of different data types.
  • Array allocates static memory and uses index/subscript for accessing elements of the array. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure.
  • Array is a pointer to the first element of it. The structure is not a pointer
  •  Array element access takes less time in comparison with structures.

36. How to Initialize Struct members with default values in C#?
C# structs cannot have a default constructor. Writing a default parameterless constructor would not compile since there is one already predefined by the compiler. 

For example, the following code would result in the compilation error, 'Structs cannot contain explicit parameterless constructors' :

public struct Employee
{
public int EmpNo;
public string LastName;
public string FirstName;
public DateTime HiredDate;
public bool IsActive;

public Employee() {
EmpNo = 0;
LastName=null;
FirstName=null;
HiredDate = new DateTime(1,1,1); 
IsActive = false;
}
}

The predefined constructor initializes all the members of the struct with its default values according to their types. For example, it initializes numeric types (int, long, float etc) to 0, bool types to false, reference types to null and DateTime types to 1/1/0001 12:00:00 AM.

37. When to use Structures?
Structs are useful simply because they are passed by value, which can actually be useful in certain algorithms. This is actually something that classes CAN'T do.

Only use a struct when you absolutely need value type semantics.


38. Classes and structs can be declared as static, Is this statement true or false?
False, only classes can be declared as static and not structs

39. How to return a structure using the function in C#?
hello
check out the code
public object FunctioName()
{
return structureObject
}
call this function
create a structure object first
SampleStructobj = new SampleStruct();

obj = (SampleStruct) FunctioName();

36.) How to Initialize Struct members with default values in C#?
C# structs cannot have a default constructor. Writing a default parameterless constructor would not compile since there is one already predefined by the compiler.

For example, the following code would result in the compilation error, 'Structs cannot contain explicit parameterless constructors' :

public struct Employee
{
public int EmpNo;
public string LastName;
public string FirstName;
public DateTime HiredDate;
public bool IsActive;

public Employee() {
EmpNo = 0;
LastName=null;
FirstName=null;
HiredDate = new DateTime(1,1,1);
IsActive = false;
}
}

The predefined constructor initializes all the members of the struct with its default values according to their types. For example, it initializes numeric types (int, long, float etc) to 0, bool types to false, reference types to null and DateTime types to 1/1/0001 12:00:00 AM.

37. When to use Structures?

Structs are useful simply because they are passed by value, which can actually be useful in certain algorithms. This is actually something that classes CAN'T do.

Only use a struct when you absolutely need value type semantics.
  • A small class may be more efficiently handled by the system if you declare it as a struct instead
  • structures have numerous limitations and no additional abilities in comparison to classes
  • stack (and as such structures) can be faster on very specialized conditions including:
  •  when the size of data chunk less than 16 bytes
  •  when no extensive boxing/unboxing is required
  • structure's members are nearly immutable.
  • the whole set of data is not big (otherwise we get stack overflow)
38. Why are mutable structs evil?
Structs are value types which means they are copied when they are passed around.

So if you change a copy you are changing only that copy, not the original and not any other copies which might be around.

If your struct is immutable then all automatic copies resulting from being passed by value will be the same.

If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)

39. What does the keyword “new” does to a struct in C#?

When you "new" a value type, three things happen. First, the memory manager allocates space from short term storage. Second, the constructor is passed a reference to the short term storage location. After the constructor runs, the value that was in the short-term storage location is copied to the storage location for the value, wherever that happens to be. Remember, variables of value type store the actual value.

40 Why Structures can not be inherited?
Structures are by value type and value types are by default sealed so we cannot inherit structure. The reason is that most inheritance techniques relate to runtime polymorphism (virtual functions) and those don’t work on value types: for runtime polymorphism to have any meaning, objects need to be treated as references – this isn’t specific to .NET either, it’s simply a technical detail of how virtual functions are implemented.



1 comment:

Unknown said...

I’m thoroughly impressed with your expertise blog. You are decide to helping us…..this is very good initiative. Thank you very much.

You can also visit:

BULK SMS SERVICE PROVIDER UAE
BULK SMS SERVICE PROVIDER IN INDIA
BULK SMS SERVICE PROVIDER IN DELHI