Sie sind auf Seite 1von 12

Dot Net Framework for Application Development (17CS564) 2019

MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE


DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
2019-20 (Odd Semester)

Subject: Dot Net Framework for Application Development Subject Code: 17CS564
Section: 5th „B‟ Staff Name: Honnaraju .B
MODULE 3

1. Explain the concept of params array with programming example. (06 Marks)
Answer:
Declaring a params array
Using a params array, you can pass a variable number of arguments to a method. You
indicate a params array by using the params keyword as an array parameter modifier when
you define the method parameters. For example, here‟s Min again—this time with its array
parameter declared as a params
array:
class Util
{
public static int Min(params int[] paramList)
{
// code exactly as before
}
}
The effect of the params keyword on the Min method is that it allows you to call the method by
using any number of integer arguments without worrying about creating an array. For
example, to find the minimum of two integer values, you can simply write this:
int min = Util.Min(first, second);
The compiler translates this call into code similar to this:

int[] array = new int[2];


array[0] = first;
array[1] = second;
int min = Util.Min(array);
To find the minimum of three integer values, you write the code shown here, which is also
converted by the compiler to the corresponding code that uses an array:
int min = Util.Min(first, second, third);
Both calls to Min (one call with two arguments and the other with three arguments) resolve to
the same Min method with the params keyword. And, as you can probably guess, you can call
this Min method with any number of int arguments. The compiler just counts the number of
int arguments, creates an int array of that size, fills the array with the arguments, and then
calls the method by passing the single array parameter.
public class Program
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}

public static void UseParams2(params object[] list)


{
for (int i = 0; i < list.Length; i++)

1 Dept. of CSE, Maharaja Institute of Technology Mysore.


Dot Net Framework for Application Development (17CS564) 2019

{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}

public static void Main()


{
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");
UseParams2();
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);
object[] myObjArray = { 2, 'b', "test", "again" };
UseParams2(myObjArray);
UseParams2(myIntArray);
}
}

2. Define Inheritance. Explain how to create a derived class that inherits features from a
baseclass, with an example program.
Answer: (06 Marks)
One of the most important concepts in object-oriented programming is inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of
an existing class. This existing class is called the base class, and the new class is referred to
as the derived class.
You declare that a class inherits from another class by using the following syntax:
class BaseClass
{
……………..
}
class DerivedClass : BaseClass
{
...
}
The derived class inherits from the base class, and the methods in the base class become part
of the derived class.
Example:
namespace InheritanceTest
{
public class Add1
{
public int a;
public void Read()
{
a = 20;
}
}
public class Add2: Add1
{
int b;
public void ReadVal()
{
2 Dept. of CSE, Maharaja Institute of Technology Mysore.
Dot Net Framework for Application Development (17CS564) 2019

b = 20;
}
public int Sum()
{
int res = a + b;
return(res);
}
}
public class Program
{
public static void Main(string[] args)
{
Add2 A = new Add2();
A.Read();
A.ReadVal();
int res= A.Sum();
Console.WriteLine("Sum of two number is = {0}",res);
}
}
}

3. Explain how to manage system resources by using Garbage collector.


Answer: (06 Marks)
Sometimes it‟s inadvisable to release a resource in a destructor; some resources are
just too valuable to lie around waiting for an arbitrary length of time until the garbage
collector actually releases them. Scarce resources such as memory, database connections, or
file handles need to be released, and they need to be released as soon as possible. In these
situations, your only option is to release the resource yourself. You can achieve this by
creating a disposal method—a method that explicitly disposes of a resource. If a class has a
disposal method, you can call it and control when the resource is released.
Disposal methods
An example of a class that implements a disposal method is the TextReader class from
the System.IO namespace. This class provides a mechanism to read characters from a
sequential stream of input. The TextReader class contains a virtual method named Close,
which closes the stream. The StreamReader class (which reads characters from a stream, such
as an open file) and the StringReader class (which reads characters from a string) both derive
from TextReader, and both override the Close method. Here‟s an example that reads lines of
text from a file by using the StreamReader class and then displays them on the screen:
TextReader reader = new StreamReader(filename);
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
reader.Close();

Exception-safe disposal
One way to ensure that a disposal method (such as Close) is always called, regardless of
whether there is an exception, is to call the disposal method within a finally block. Here‟s the
preceding example coded by using this technique:
TextReader reader = new StreamReader(filename);
try
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
3 Dept. of CSE, Maharaja Institute of Technology Mysore.
Dot Net Framework for Application Development (17CS564) 2019

}
finally
{
reader.Close();
}

The using statement and the IDisposable interface


The using statement provides a clean mechanism for controlling the lifetimes of resources. You
can create an object, and this object will be destroyed when the using statement block
finishes.
The syntax for a using statement is as follows:
using ( type variable = initialization )
{
StatementBlock
}
Calling the Dispose method from a destructor
When writing your own classes, should you write a destructor or implement the IDisposable
interface so that instances of your class can be managed by a using statement? A call to a
destructor will happen, but you just don‟t know when. On the other hand, you know exactly
when a call to the Dispose method happens, but you just can‟t be sure that it will actually
happen because it relies on the programmer who is using your classes to remember to write a
using statement. However, it is possible to ensure that the Dispose method always runs by
calling it from the destructor.

4. Explain how to implement interface in a class with programming example.


Answer: (06 Marks)
To implement an interface, you declare a class or structure that inherits from the interface
and that implements all the methods specified by the interface. This is not really inheritance
as such, although the syntax is the same.
For example, suppose that you are defining the Mammal hierarchy.

You could define the ILandBound interface that contains this method as follows:
interface ILandBound
{
int NumberOfLegs();
}
You could then implement this interface in the Horse class. You inherit from the interface and
provide an implementation of every method defined by the interface (in this case, there is just
the one method,NumberOfLegs).
class Horse : ILandBound
{
...
public int NumberOfLegs()
{
return 4;
}
}
When you implement an interface, you must ensure that each method matches its
corresponding interface method exactly, according to the following rules:
 The method names and return types match exactly.
 Any parameters (including ref and out keyword modifiers) match exactly.
 All methods implementing an interface must be publicly accessible. However, if you are
using an explicit interface implementation, the method should not have an access
qualifier.
If there is any difference between the interface definition and its declared implementation, the
class will not compile.
Example:
using System;
4 Dept. of CSE, Maharaja Institute of Technology Mysore.
Dot Net Framework for Application Development (17CS564) 2019

namespace InterfaceDemo
{
interface IUser
{
void GetDetails(string x);
}
class User : IUser
{
public void GetDetails(string a)
{
Console.WriteLine("Name: {0}", a);
}
}
class User1 : IUser
{
public void GetDetails(string a)
{
Console.WriteLine("Location: {0}", a);
}
}
class Program
{
static void Main(string[] args)
{
IUser u = new User();
u.GetDetails("Kumar");
IUser u1 = new User1();
u1.GetDetails("Mysore");
}
}
}

5. Explain Sealed classes and Sealed methods in brief. (04 Marks)


Answer:
Sealed Classes and Class Members
Classes can be declared as sealed by putting the keyword sealed before the class
definition. For example:
public sealed class D
{
// Class members here.
}
A sealed class cannot be used as a base class. For this reason, it cannot also be an
abstract class. Sealed classes prevent derivation. Because they can never be used as a base
class, some run-time optimizations can make calling sealed class members slightly faster.
A method, indexer, property, or event, on a derived class that is overriding a virtual
member of the base class can declare that member as sealed. This negates the virtual aspect
of the member for any further derived class. This is accomplished by putting
the sealed keyword before the override keyword in the class member declaration. For example:
public class D : C
{
public sealed override void DoWork() { }
}

6. Define method overriding. Explain different forms of override a method with example.
Answer: (08 Marks)
Method overriding is a feature that allows you to invoke functions (that have the same
signatures) that belong to different classes in the same hierarchy of inheritance using the base

5 Dept. of CSE, Maharaja Institute of Technology Mysore.


Dot Net Framework for Application Development (17CS564) 2019

class reference. C# makes use of two keywords: virtual and overrides to accomplish Method
overriding
There are the following 3 types of keywords used in C# for method overriding:
 virtual
 override
 new and base
Declaring new methods
One of the hardest tasks in the realm of computer programming is thinking up unique and
meaningful names for identifiers. If you are defining a method for a class and that class is part
of an inheritance hierarchy, sooner or later you are going to try to reuse a name that is
already in use by one of the classes further up the hierarchy. If a base class and a derived
class happen to declare two methods that have the same signature, you will receive a warning
when you compile the application.
You can silence the warning by using the new keyword, as follows:
class Mammal
{
...
public void Talk()
{
...
}
}
class Horse : Mammal
{
...
new public void Talk()
{
...
}
}
Using the new keyword like this does not change the fact that the two methods are completely
unrelated and that hiding still occurs.

Declaring virtual methods


Sometimes, you do want to hide the way in which a method is implemented in a base class.
A method that is intended to be overridden is called a virtual method.
You can mark a method as a virtual method by using the virtual keyword. For example, the
ToString method in the System.Object class is defined like this:
namespace System
{
class Object
{
public virtual string ToString()
{
...
}
...
}
...
}

Declaring override methods


If a base class declares that a method is virtual, a derived class can use the override keyword
to declare another implementation of that method, as demonstrated here:
class Horse : Mammal
{
...
public override string ToString()
6 Dept. of CSE, Maharaja Institute of Technology Mysore.
Dot Net Framework for Application Development (17CS564) 2019

{
...
}
}
The new implementation of the method in the derived class can call the original
implementation of the method in the base class by using the base keyword, like this:
public override string ToString()
{
string temp = base.ToString();
...
}
Example:
using System;
namespace Hello_Word
{
class baseClass
{
public virtual void Greetings()
{
Console.WriteLine("baseClass Saying Hello!");
}
}
class subClass : baseClass
{
public override void Greetings()
{
base.Greetings();
Console.WriteLine("subClass Saying Hello!");
}
}
class Program
{
static void Main(string[] args)
{
baseClass obj1 = new subClass();
obj1.Greetings();
Console.ReadLine();
}
}
}

7. Write a C# program that has class “TwoDshape” with fields dim1 and dim2 and a
method area( ). Inherit two classes “Triangle” and “Rectangle” for “TwoDshape” and
override method area( ) to calculate area of triangle and rectangle respectively.
Instantiate objects of all classes. (08 Marks)
Answer:
using System;
class TwoDshape
{
public int Dim1, Dim2;
public double Res;
public void Read(int a, int b)
{
Dim1 = a;
Dim2 = b;
}
public virtual void Area()
{
7 Dept. of CSE, Maharaja Institute of Technology Mysore.
Dot Net Framework for Application Development (17CS564) 2019

}
}
class Triangle : TwoDshape
{
public override void Area()
{
Res= 0.5 * Dim1 * Dim2;
Console.WriteLine("Area of Triangle is = {0}", Res);
}
}
class Rectangle : TwoDshape
{
public override void Area()
{
Res= Dim1 * Dim2;
Console.WriteLine("Area of Rectangle is = {0}", Res);
}
}
public class Program
{
public static void Main()
{
Triangle Tri = new Triangle();
int d1,d2;
Console.WriteLine("Enter the value for d1 and d2 to find Area of Triangle");
d1 = Convert.ToInt32(Console.ReadLine());
d2 = Convert.ToInt32(Console.ReadLine());
Tri.Read(d1,d2);
Tri.Area();
Rectangle Rect = new Rectangle();
Console.WriteLine("Enter the value for d1 and d2 to find Area of Rectangle");
d1 = Convert.ToInt32(Console.ReadLine());
d2 = Convert.ToInt32(Console.ReadLine());
Rect.Read(d1,d2);
Rect.Area();
}
}
Output:
Enter the value for d1 and d2 to find Area of Triangle
3
3
Area of Triangle is = 4.5
Enter the value for d1 and d2 to find Area of Rectangle
5
3
Area of Rectangle is = 15

8. Explain the steps taken by the garbage collector to destroy objects.


Answer: (05 Marks)
The steps that the garbage collector takes are as follows:
1. It builds a map of all reachable objects. It does this by repeatedly following reference fields
inside objects. The garbage collector builds this map very carefully and ensures that circular
references do not cause infinite recursion. Any object not in this map is deemed to be
unreachable.
2. It checks whether any of the unreachable objects has a destructor that needs to be run (a
process called finalization). Any unreachable object that requires finalization is placed in a
special queue called the freachable queue (pronounced “F-reachable”).

8 Dept. of CSE, Maharaja Institute of Technology Mysore.


Dot Net Framework for Application Development (17CS564) 2019

3. It deallocates the remaining unreachable objects (those that don‟t require finalization) by
moving the reachable objects down the heap, thus defragmenting the heap and freeing
memory at its top. When the garbage collector moves a reachable object, it also updates any
references to the object.
4. At this point, it allows other threads to resume.
5. It finalizes the unreachable objects that require finalization (now in the freachable queue)
by running the Finalize methods on its own thread.

9. Mention the difference between interface and class. (04 Marks)


Answer:
Difference between Interface and Class
1. A class can contain data members and methods with the complete definition. An
interface contains the only signature of members.
2. A class can only be inherited from a single class but can be inherited from more than
one interfaces.
3. Interfaces are always implemented whereas classes are extended.
4. Classes represent the “real object” and do all the work. Interfaces allow you to create a
program that will manipulate the class in a predefined way.

10. Write a C# program using multilevel inheritance. (06 Marks)


Answer:
using System;
public class Animal
{
public void eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public void bark()
{
Console.WriteLine("Barking...");
}
}
public class BabyDog : Dog
{
public void weep()
{
Console.WriteLine("Weeping...");
}
}
class TestInheritance2
{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();

9 Dept. of CSE, Maharaja Institute of Technology Mysore.


Dot Net Framework for Application Development (17CS564) 2019

}
}

11. Difference between method overloading and method overriding. (04 Marks)
Answer:
Difference between method overloading and method overriding
1. In Method overloading methods must have a different signature. In method, overriding
methods must have the same signature.
2. Function Overloading is to “add” or “extend” more to method‟s behaviour. Function
overriding is to completely “change” or “redefine” the behaviour of a method.
3. Method overloading is used to achieve Compile time polymorphism; method overriding is
used to achieve run-time polymorphism.
4. In method/function overloading compiler knows which object assigned to which class at
the time of compilation, but in method overriding this information is not known till
runtime.
5. Function Overloading takes place in the same class whereas Overriding takes place in a
class derived from a base class.

12. Define interface. How it declared and accessed? Demonstrate with an example.
Answer: (08 Marks)
Like a class, Interface can have methods, properties, events, and indexers as its members.
But interfaces will contain only the declaration of the members. The implementation of
interface‟s member will be given by class who implements the interface implicitly or explicitly.
Defining an interface
Defining an interface is syntactically similar to defining a class, except that you use the
interface keyword instead of the class keyword. Within the interface, you declare methods
exactly as in a class or structure, except that you never specify an access modifier (public,
private, or protected). Additionally, the methods in an interface have no implementation; they
are simply declarations, and all types that implement the interface must provide their own
implementations. Consequently, you replace the method body with a semicolon.
Syntax:
interface InterfaceName
{
returnType methodName(paramType paramName...);
}

To implement an interface, you declare a class or structure that inherits from the interface
and that implements all the methods specified by the interface. This is not really inheritance
as such, although the syntax is the same.
For example, suppose that you are defining the Mammal hierarchy.

You could define the ILandBound interface that contains this method as follows:
interface ILandBound
{
int NumberOfLegs();
}
You could then implement this interface in the Horse class. You inherit from the interface and
provide an implementation of every method defined by the interface (in this case, there is just
the one method,NumberOfLegs).
class Horse : ILandBound
{
...
public int NumberOfLegs()
{
return 4;
}
}

10 Dept. of CSE, Maharaja Institute of Technology Mysore.


Dot Net Framework for Application Development (17CS564) 2019

When you implement an interface, you must ensure that each method matches its
corresponding interface method exactly, according to the following rules:
 The method names and return types match exactly.
 Any parameters (including ref and out keyword modifiers) match exactly.
 All methods implementing an interface must be publicly accessible. However, if you are
using an explicit interface implementation, the method should not have an access
qualifier.
If there is any difference between the interface definition and its declared implementation, the
class will not compile.
Example:
using System;
namespace InterfaceDemo
{
interface IUser
{
void GetDetails(string x);
}
class User : IUser
{
public void GetDetails(string a)
{
Console.WriteLine("Name: {0}", a);
}
}
class User1 : IUser
{
public void GetDetails(string a)
{
Console.WriteLine("Location: {0}", a);
}
}
class Program
{
static void Main(string[] args)
{
IUser u = new User();
u.GetDetails("Kumar");
IUser u1 = new User1();
u1.GetDetails("Mysore");
}
}
}

13. Explain abstract class and abstract method, with syntax and example.
Answer: (08 Marks)
Abstract Classes and Class Members
Classes can be declared as abstract by putting the keyword abstract before the class
definition. For example:
public abstract class A
{
// Class members here.
}

An abstract class cannot be instantiated. The purpose of an abstract class is to provide


a common definition of a base class that multiple derived classes can share. For example, a
class library may define an abstract class that is used as a parameter to many of its functions,
and require programmers using that library to provide their own implementation of the class
by creating a derived class.
11 Dept. of CSE, Maharaja Institute of Technology Mysore.
Dot Net Framework for Application Development (17CS564) 2019

Abstract classes may also define abstract methods. This is accomplished by adding the
keyword abstract before the return type of the method. For example:
public abstract class A
{
public abstract void DoWork(int i);
}

Abstract methods have no implementation, so the method definition is followed by a semicolon


instead of a normal method block. Derived classes of the abstract class must implement all
abstract methods. When an abstract class inherits a virtual method from a base class, the
abstract class can override the virtual method with an abstract method. For example:
// compile with: -target:library
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}

public abstract class E : D


{
public abstract override void DoWork(int i);
}

public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}

If a virtual method is declared abstract, it is still virtual to any class inheriting from the
abstract class. A class inheriting an abstract method cannot access the original
implementation of the method—in the previous example, DoWork on class F cannot
call DoWork on class D. In this way, an abstract class can force derived classes to provide new
method implementations for virtual methods.
public abstract class Animal
{
protected string name;
public abstract string sound(); //all classes that implement Animal must have a
// sound method
}
public class Cat : Animal
{
public Cat()
{
this.name = "Garfield";
}
override public string sound()
{ //implemented sound method from the abstract class & method
return "Meow!";
}
}

12 Dept. of CSE, Maharaja Institute of Technology Mysore.

Das könnte Ihnen auch gefallen