Saturday, 28 August 2021

Constructor

1. What is a Constructor in C#?

A constructor is a special method that runs when an object of a class is created. It initializes the object and allocates memory. The constructor has the same name as the class and does not have a return type.

Key Points:

  • Same name as the class.
  • No return type, not even void.
  • Can have parameters.
  • Can have access modifiers.
  • Cannot return a value, but can use return;.

2. Can we define a method with the same name as the class in C#?

No, you cannot have a method with the same name as the class. It will result in a compile-time error.


3. How many types of constructors are there in C#?

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • Static Constructor
  • Private Constructor

4. What is a Default Constructor?

A default constructor has no parameters. It can be:

  • System-defined: Automatically provided by C#.
  • User-defined: Explicitly created by the developer.

5. When should we define a Parameterized Constructor?

Use a parameterized constructor when you want to initialize an object with specific values provided by the user.


6. What is a Parameterized Constructor?

A parameterized constructor allows you to set different values for each instance of a class. This way, you can create objects with distinct initial values.


7. How many constructors can be defined in a class?

You can define multiple constructors in a class as long as they have different parameter types or orders. This includes one default constructor and any number of parameterized constructors.


8. What is a Copy Constructor in C#?

A copy constructor takes an object of the same class as a parameter and initializes a new object with the values from that existing object.


9. Explain the Static Constructor in C#.

A static constructor is called once, regardless of how many instances of the class are created. It's used to initialize static fields and cannot have parameters or access modifiers.


10. What is a Private Constructor in C#?

A private constructor restricts object creation from outside the class. It's often used in design patterns like Singleton, ensuring only one instance of the class exists.


11. When is a Destructor called?

A destructor is called automatically when an object is destroyed, usually by the garbage collector.


12. When does an object get destroyed?

An object can be destroyed when:

  1. The program ends.
  2. The garbage collector runs due to memory pressure.
  3. You explicitly call GC.Collect().

13. Can a child class call the constructor of a base class?

Yes, a child class can call a base class constructor using the base keyword.


14. Which constructor is called first when a child class instance is created?

The base class constructor is called first, followed by the child class constructor.


15. Can you mark a static constructor with access modifiers?

No, static constructors cannot have access modifiers.


16. Can static constructors have parameters?

No, static constructors cannot accept parameters.


17. Give two scenarios where static constructors can be useful.

  • Initializing a log file for a class.
  • Loading unmanaged code with LoadLibrary.

18. What is a Destructor?

A destructor is a method that is called when an instance of a class is destroyed. It has the same name as the class, prefixed with a tilde (~).


19. Can a class have more than one destructor?

No, a class can only have one destructor.


20. Can you pass parameters to destructors?

No, destructors cannot take parameters and cannot be overloaded.


21. Can you explicitly call a destructor?

No, destructors are automatically invoked by the garbage collector.


22. When should you use a Private Constructor?

  • To prevent instantiation from outside the class.
  • To implement the Singleton design pattern.
  • When some constructors should only be used internally.

23. If a class has a parameterized constructor, do you need a default constructor?

If you have a parameterized constructor, you need to define a default constructor explicitly if you want one.


24. Can constructors be inherited?

No, constructors cannot be inherited.


25. How can you call a base class constructor from a child class?

You can call a base class constructor using the base keyword in the child class constructor.


26. In which order are constructors called in inheritance?

When creating an object of a derived class, the base class constructor is called first, followed by the derived class constructor.


27. Can constructors be overloaded?

Yes, constructors can be overloaded by varying parameters.


28. How do you overload a constructor?

You overload a constructor by defining it with different parameter types or numbers.


29. How do you call one constructor from another in the same class?

You can call one constructor from another using the this keyword.


30. Which constructor is called first when you create an object of a class?

The first overloaded constructor is called, followed by the default constructor if it exists.


31. Can a constructor call itself using the this keyword?

No, doing so will result in a compile-time error.


32. Does memory get allocated when a constructor is called?

Yes, memory is allocated using the new operator when a constructor is invoked.

Saturday, 21 August 2021

Programming Related Question Answers

 1. How to reverse a string?

string aa = "Hello World!";

string str = new string(aa.Reverse().ToArray());

                                    OR

string aa = "Hello World!";

var result = aa.ToCharArray().Reverse();

Console.WriteLine(new string(result.ToArray()));

                                    OR

internal static void ReverseString(string str) 

    char[] charArray = str.ToCharArray(); 

    for (int i = 0, j = str.Length - 1; i < j; i++, j--) 

    { 

        charArray[i] = str[j]; 

        charArray[j] = str[i]; 

    } 

    string reversedstring = new string(charArray); 

    Console.WriteLine(reversedstring); 

}

 

2. Prime number?

public static bool IsPrimeNumbers(int number) 

    bool returnMsg = false; 

    for (int i = 2; i <= number; i++) 

    { 

        if ((number % i) == 0 && number != i) 

        { 

            returnMsg = false; 

            return returnMsg; 

        } 

        else if (number == i) 

        { 

            returnMsg = true; 

            return returnMsg; 

        } 

    } 

    return returnMsg; 

} 

 

3. Fibonacci series?

public static void PrintFibonacciSeries(int limit) 

    int digit1, digit2, digit3; 

    digit1 = 0; 

    digit2 = 1; 

    digit3 = digit1 + digit2; 

    Console.WriteLine(digit1); 

    Console.WriteLine(digit2); 

    Console.WriteLine(digit3); 

    for (int i = 0; i < limit; i++) 

    { 

        digit1 = digit2; 

        digit2 = digit3; 

        digit3 = digit1 + digit2; 

        Console.WriteLine(digit3); 

    } 

} 

 

4. How to find if the given string is a palindrome or not?

public bool isPalindrome(string myString)

{

    string string1, rev;

    string1 = "Malayalam";

    char[] ch = string1.ToCharArray();

    Array.Reverse(ch);

    rev = new string(ch);

    bool b = string1.Equals(rev, StringComparison.OrdinalIgnoreCase);

    if (b == true)

    {

        Console.WriteLine("" + string1 + " is a Palindrome!");

    }

    else

    {

        Console.WriteLine(" " + string1 + " is not a Palindrome!");

    }

 

    return b;

}

 

5. Get Factorial of number.

public static int PrintFactorialOfNumber(int number) 

    // 5*4 

    int result = 1; 

    for (int i = number; i > 0; i--) 

    { 

        result = result * i; 

    } 

    return result; 

} 

 

6. How to remove duplicate characters from a string?

internal static void removeduplicate(string str) 

 { 

     string result = string.Empty; 

 

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

     { 

         if (!result.Contains(str[i])) 

         { 

             result += str[i]; 

         } 

     } 

     Console.WriteLine(result); 

 }


7. Find third Max salary using LINQ?

List<Employee> employees = new List<Employee>()

            {

                new Employee { Id = 1, UserName = "Anil" , Salary = 5000},

                new Employee { Id = 2, UserName = "Sunil" , Salary = 6000},

                new Employee { Id = 3, UserName = "Lokesh" , Salary = 8000},

                new Employee { Id = 4, UserName = "Vinay" , Salary = 7000},

                new Employee { Id = 5, UserName = "Amit" , Salary = 8000},

                new Employee { Id = 6, UserName = "Lokesh" , Salary = 5500},

                new Employee { Id = 7, UserName = "Mahesh" , Salary = 7000}

            };

var emp = employees.GroupBy(e => e.Salary).OrderByDescending(g => g.Key).Skip(2).First();


8. Join in LINQ?

var query = from department in departments

    join employee in employees

   on department.ID equals employee.DepartmentID 

   select new { employee.Name, Department = department.Name };


9. Left Outer Join in LINQ?

var Ljoin  =    from emp in ListOfEmployees

join proj in ListOfProject

on emp.ProjectID equals proj.ProjectID into JoinedEmpDept

from proj in JoinedEmpDept.DefaultIfEmpty()

select new

{

EmployeeName = emp.Name,

ProjectName = proj != null ? proj.ProjectName : null

};



SQL Server Query Related Questions and Answers


1. Write an SQL query to print the first three characters of  FIRST_NAME from Worker table.
Select substring(FIRST_NAME,1,3) from Worker;

2. Write an SQL query to find the position of the alphabet (‘a’) in the first name column ‘Amitabh’ from Worker table.
Select INSTR(FIRST_NAME, BINARY'a') from Worker where FIRST_NAME = 'Amitabh';

3. Write an SQL query to print the FIRST_NAME from Worker table after replacing ‘a’ with ‘A’.
Select REPLACE(FIRST_NAME,'a','A') from Worker;

4. Write an SQL query to print details for Workers with the first name as “Vipul” and “Satish” from Worker table.
Select * from Worker where FIRST_NAME in ('Vipul','Satish');

5. Write an SQL query to print details of workers excluding first names, “Vipul” and “Satish” from Worker table.
Select * from Worker where FIRST_NAME not in ('Vipul','Satish');

6. Write an SQL query to print details of Workers with DEPARTMENT name as “Admin”.
Select * from Worker where DEPARTMENT like 'Admin%';

7. Write an SQL query to fetch the no. of workers for each department in the descending order.
SELECT DEPARTMENT, count(WORKER_ID) No_Of_Workers 
FROM worker 
GROUP BY DEPARTMENT 
ORDER BY No_Of_Workers DESC;

8. Write an SQL query to determine the nth (say n=5) highest salary from a table.
SELECT TOP 1 Salary
FROM (
 SELECT DISTINCT TOP n Salary
 FROM Worker 
 ORDER BY Salary DESC
 ) as temp
ORDER BY Salary ASC;

9. Write an SQL query to fetch nth max salaries from a table.
SELECT distinct Salary from worker a WHERE n >= (SELECT count(distinct Salary) from worker b WHERE a.Salary <= b.Salary) order by a.Salary desc;

10. Write an SQL query to show the second highest salary from a table.
Select max(Salary) from Worker 
where Salary not in (Select max(Salary) from Worker);

11. Write an SQL query to fetch the list of employees with the same salary.
Select distinct W.WORKER_ID, W.FIRST_NAME, W.Salary 
from Worker W, Worker W1 
where W.Salary = W1.Salary 
and W.WORKER_ID != W1.WORKER_ID;

12. Write an SQL query to fetch the first 50% records from a table.
SELECT * FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);

13. Write an SQL query to fetch the departments that have less than five people in it.
SELECT DEPARTMENT, COUNT(WORKER_ID) as 'Number of Workers' 
FROM Worker 
GROUP BY DEPARTMENT 
HAVING COUNT(WORKER_ID) < 5;

14. Write an SQL query to show all departments along with the number of people in there.
SELECT DEPARTMENT, COUNT(DEPARTMENT) as 'Number of Workers' 
FROM Worker 
GROUP BY DEPARTMENT;

15. Write an SQL query to print the name of employees having the highest salary in each department.
SELECT t.DEPARTMENT,t.FIRST_NAME,t.Salary from(SELECT max(Salary) as TotalSalary,DEPARTMENT from Worker group by DEPARTMENT) as TempNew 
Inner Join Worker t on TempNew.DEPARTMENT=t.DEPARTMENT 

 and TempNew.TotalSalary=t.Salary;

16. Delete duplicate rows from a SQL Server Table?
DELETE FROM [Employee]
    WHERE ID NOT IN
    (
        SELECT MAX(ID) AS MaxRecordID
        FROM [Employee]
        GROUP BY [FirstName],[LastName],[Country]
    );

Using CTE:

WITH CTE([FirstName],[LastName],[Country],DuplicateCount)
AS (SELECT [FirstName],[LastName],[Country],
           ROW_NUMBER() OVER(PARTITION BY [FirstName],[LastName],[Country]
           ORDER BY ID) AS DuplicateCount
    FROM [Employee])

DELETE FROM CTE
WHERE DuplicateCount > 1;


Constructor

1. What is a Constructor in C#? A constructor is a special method that runs when an object of a class is created. It initializes the object ...