Seventh Semester B.E. IA Test-I, 2014 USN 1 P E I S PES INSTITUTE OF TECHNOLOGY C# solution set for T1 Answer any 5 of the Following Questions 1) What is.net? With a neat diagram explain the important building blocks of.net platform? (10Marks) solution: From a programmers point of view,.net can be understood as a new runtime environment and a comprehensive base class library. CLR (Common Language Runtime) To locate, load, and manage.net types Automatic memory management, language integration, and type safety CTS (Common Type System) Describes all possible data types and programming constructs supported by the runtime CLS (Common Language Specification) A set of rules that defines a subset of types and specifications CLR sits on top of OS (same as JVM of Java) CLR loads modules containing executables and executes them Code may be managed or unmanaged Managed code consists of instructions in pseudo random code called CIL (Common Intermediate Language). CIL instructions are JIT compiled into native machine code at runtime JIT compiled methods reside in cache until the applications life time Advantages of managed code: type safety, memory management, and code verification security CLR can translate code from C#, J#, C, C++, VB, and Jscript into CIL. CLR doesnt launch a new process for every application. It launches one process and hosts individual applications in application domains Encapsulates various primitives like: threads, file IO, graphical rendering, and other interaction with HW devices
It also provides: database manipulation, XML integration, Web-enabled front-end. C# &.NET Programming Notes Ms Renuka, Asst Prof,ISE Dept, PESIT(BSC) Similar to Javas System namespace. Used by all.net applications Has classes for IO, threading, database, text, graphics, console, sockets/web/mail, security, cryptography, COM, run-time type discovery/invocation, assembly generation Encapsulate various primitives Provide support for a number of services required by most real-world applications Be broken into a number of discrete assemblies Common type system(cts) CTS is a formal specification that describes how a given type must be defined for CLR CTS Class Type CTS Structure Type CTS Interface Type CTS Enumeration type CTS Delegate type Same as C++ class Can contain members: methods, properties, events, etc. Support for abstract members that define a polymorphic interface for derived classes Multiple inheritance is not allowed "sealed"? sealed classes can't function as base classes Implement any interfaces? An interface is a collection of abstract members Abstract or Concrete? Abstract classes (to define common behaviors for derived) can't be created directly but concrete classes can. Visibility? visibility attribute to know whether external assemblies can use it. CTS Structure types C# &.NET Programming Notes Ms Renuka, Asst Prof,ISE Dept, PESIT(BSC) Same as C/C++ Derived from a common base class System.ValueType CTS Interface Type Same as pure abstract class of C++ A description of work that a derived class can perform Similar to a class, but can never be instantiated CTS Enumeration type To group name/value pairs under a specific name Default Storage: System.Int32 (could be changed) CTS Delegate type Same as C's function pointer (System.MulticastDelegate) Useful for event handling (ASP.NET) 2) a) What is boxing and unboxing? Explain with Programming examples. (5Marks) solution: Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type by storing the variable in a System.Object.
When you box a value, the CLR allocates a new object on the heap and copies the value type s value into that instance. What is returned to you is a reference to the newly allocated object. int Val = 1; Object Obj = Val; //Boxing The first line we created a Value Type Val and assigned a value to Val. The second line, we created an instance of Object Obj and assign the value of Val to Obj. From the above operation (Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type. These types of operation is called Boxing. int Val = 1; Object Obj = Val; //Boxing int i = (int)obj; //Unboxing The first two line shows how to Box a Value Type. The next line (int i = (int) Obj) shows extracts the Value Type from the Object. That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing Example program using System; class TestBoxingExample public static void Main() int i = 0; object obj = (object) i; // i is boxed here obj = ((int) i) + 3; // changing i on the heap i += 1; // changing i on the stack Console.WriteLine(obj.ToString()); Console.WriteLine(i.ToString());
b) Explain any three instance methods and static methods of System.Object. (5Marks) solution: In.NET, every type is ultimately derived from a common base class: System.Object. The Object class defines a common set of members supported by every type in the.net universe. When you create a class that does not explicitly specify its base class, you implicitly derive from System.Object: It is known that every data type(valuetype or Reference type) is ultimately derived from a common base class: System.Object. Thus it is known as Master Node. The Object class defines a common polymorphic behavior for every type in the.net universe. Implicitly, It identifies the base class and derived classes and makes the difference between them. The topmost class in the.net world: System.Object namespace System public class Object public Object(); public virtual Boolean Equals(Object obj); public virtual Int32 GetHashCode(); public Type GetType(); public virtual String ToString(); protected virtual void Finalize(); protected Object MemberwiseClone(); public static bool Equals(object obja, object objb); public static bool ReferenceEquals(object obja, object objb);
Two static members of System.Object are as follows: Object.Equals():Check the equality of value based members Object.ReferenceEquals(): Check the equality of reference based members 5. 3) Explain CLR. Illustrate the work flow that take place between source code, given.net compiler and the.net execution engine. (10Marks)
solution : CLR(Common Language runtime) sits on top of OS (same as JVM of Java) CLR loads modules containing executables and executes them Managed code consists of instructions in pseudo random code called CIL (Common Intermediate Language). CIL instructions are JIT compiled into native machine code at runtime JIT compiled methods reside in cache until the applications life time CLR can translate code from C#, J#, C, C++, VB, and Jscript into CIL. CLR doesnt launch a new process for every application. It launches one process and hosts individual applications in application domains The crux of the CLR is physically represented by a library named mscoree.dll (aka the Common Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is loaded automatically, which in turn loads the required assembly into memory. The runtime engine is responsible for a number of tasks. First and foremost, it is the entity in charge of resolving the location of an assembly and finding the requested type within the binary by reading the contained metadata. The CLR then lays out the type in memory, compiles the associated CIL into platform-specific instructions, performs any necessary security checks, and then executes the code in question. In addition to loading your custom assemblies and creating your custom types, the CLR will also interact with the types contained within the.net base class libraries when required. Although the entire base class library has been broken into a number of discrete assemblies, the key assembly is mscorlib.dll. mscorlib.dll contains a large number of C# &.NET Programming Notes Ms Renuka, Asst Prof,ISE Dept, PESIT(BSC) core types that encapsulate a wide variety of common programming tasks as well as the core data types used by all.net languages. When you build.net solutions, you automatically have access to this particular assembly.
4) Write a C# code to Create a type MyPoint (named p1) that is then assigned to another MyPoint (p2) (p1==p2) MyPoint is a value type, you have two copies of the MyPoint type on the stack,(p1.x=400,p1.y=400,p2.x,p2.y) each of which can be independently manipulated. display the contents.change the value of p2.x=800 change the definition of the MyPoint type from a C# structure to a C# class and display the changed result. (10 Marks) solution: using System; namespace valrefclass // Change struct to class to see the different behaviors.class-reference type class FOO public int x, y; // Assignment of reference types copies the reference class valreffooclass public static int Main(string[] args) Console.WriteLine("***** Value types & Ref Types *****"); FOO f1 = new FOO(); f1.x = 100; f1.y = 100; // Here is F1. Console.WriteLine("F1.x = 0", f1.x); Console.WriteLine("F1.y = 0", f1.y); Console.WriteLine("-> Assigning f2 to f1."); FOO f2 = f1; // Here is F2. Console.WriteLine("F2.x = 0", f2.x); Console.WriteLine("F2.y = 0", f2.y); // Change f2.x. This will NOT change f1.x. Console.WriteLine("-> Changing f2.x"); f2.x = 900; // Print again. Console.WriteLine("-> Here are the X s again...");
Console.WriteLine("F2.x = 0", f2.x); Console.WriteLine("F1.x = 0\n", f1.x); return 0; 5) Explain Method Parameter Modifiers in C# in detail with programming examples for each (10Marks) solution: Examples 1) None():-->The default manner in which a parameter is sent into a function is by value // Arguments are passed by value by default. public static int Add(int x, int y) int ans = x + y; // Caller will not see these changes // as you are modifying a copy of the // original data. x = 10000; y = 88888; return ans; 2) Output Parameters- Methods that have been defined to take output parameters
are under obligation to assign them to an appropriate value before exiting the method in question // Output parameters are allocated by the member. public static void Add(int x, int y, out int ans) ans = x + y; 3) Ref() using System; class Ref public static void Swap(ref int x, ref int y) int temp; temp = x; x = y; y = temp; static void Main(string[ ] args) int a = 10; int b = 20; Console.WriteLine("Before Swap => 0 \t 1", a, b); Ref.Swap(ref a, ref b); Console.WriteLine("After Swap => 0 \t 1", a, b); 4) Params using System; class Params public static void DispArrInts(string msg, params int[ ] list) Console.WriteLine(msg);
for (int i = 0; i < list.length; i++) Console.WriteLine(list[i]); static void Main(string[ ] args) int[ ] intarray = new int[ ] 1, 2, 3; DispArrInts("List1", intarray); DispArrInts("List2", 4, 5, 6, 7); // you can send more elements DispArrInts("List3", 8,9); // you can send less elements 6) a) Distinguish between Value type and Reference type with an example (5Marks) solution: Value type Reference Type When Value Types are copied, a copy is made of their values (hence the name). Directly contain their data Each has its own copy of data Operations on one cannot affect another Two types Enumeration Types Created by using enum keyword Struct Types Created by using struct keyword Built-in Simple Types: Integral Floating point Decimal Boolean Integral Types: Holds numbers often Not as simple as value types. Store references to their data (known as objects) Two reference variables can reference same object Operations on one can affect another Object reference type is stored in general memory, known as heap.(while value types are stored on the stack). new keyword is used for creating object of reference type Key words used for creating reference types are Class Interface delegate Build in reference types are
referred as int type Floating point Types: Holds numbers often referred as float type Boolean Types: Holds numbers often referred as bool type which take values as true or false. Type allocated is stack Representation of variable in local copies Derived from System.value Type they are sealed and cannot be extended Default parameter passing is pass by value Constructor can be defined,by the default constructor is reserved. Variables die when it is defined out of scope object string no need to use new keyword when declaring a new string Allocated in heap memory Pointing to memory occupied Other than System.ValueType This type can function as base to other type if it is not sealed Default parameter passing is pass by reference Constructor can be defined Variable die when When managed heap is garbage collected. b) Design a C# program to design a structure: Student <USN,Name,Mrks,Branch> here, Branch is of type enum, with members<cse, ISE,ELNS,EE,IT>. Add appropriate constructor and also a method to hike the marks by 10% to only CSE students. Show creation of some student objects and the way to call these methods. (5Marks) solution: