C#

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday 1 September 2016

Interview Question asked on immutable


Interview Question asked to me in an interview.
What will be the output of the below program ?

 using System;   
  using System.Collections.Generic;   
  using System.Linq;  
 namespace LinqDetails  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       DateTime dt = Convert.ToDateTime("9/2/2016");  
       dt.AddDays(1);  
       Console.WriteLine(dt);  
       Console.ReadLine();  
     }  
   }  
 }  

 Output







Because DateTime is immutable. :)



Common Interview question on method overloading


Is it overloaded ?What will be the output ?

using System;   
  using System.Collections.Generic;   
  using System.Linq;  
 namespace LinqDetails  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       Console.WriteLine(Add(2, 2));   
       Console.ReadLine();  
     }  
     public static double Add(int a, double b)  
     {  
       return a + b;  
     }  
     public static double Add(double a, int b)  
     {  
       return a + b;  
     }  
   }  
 }  

Output:-

Yes it is overloaded. But the above program will give an compile time error.

Error:- The call is ambiguous between the following methods or properties: 'LinqDetails.Program.Add(int, double)' and 'LinqDetails.Program.Add(double, int)'


Saturday 16 July 2016

Time Complexity of Linq methods



Took the below information from a stackoverflow answers.

There are very, very few guarantees, but there are a few optimizations:
  • Extension methods that use indexed access, such as ElementAtSkipLast or LastOrDefault, will check to see whether or not the underlying type implements IList<T>, so that you get O(1) access instead of O(N).
  • The Count method checks for an ICollection implementation, so that this operation is O(1) instead of O(N).
  • DistinctGroupBy Join, and I believe also the set-aggregation methods (UnionIntersectand Except) use hashing, so they should be close to O(N) instead of O(N²).
  • Contains checks for an ICollection implementation, so it may be O(1) if the underlying collection is also O(1), such as a HashSet<T>, but this is depends on the actual data structure and is not guaranteed. Hash sets override the Contains method, that's why they are O(1).
  • OrderBy methods use a stable quicksort, so they're O(N log N) average case.
  • Where() is O(1); it doesn't actually do any work.
    Looping through the collection returned by Where() is O(n).

How to find a string containing digits separated by '-' are consecutive

Problem Statement:

Input :- "1-2-3-4-5"
O/P:- Consecutive

Input :- "5-4-3-2-1"
O/P:- Consecutive

Input :- "1-4-3-2-5"
O/P:- Not Consecutive


Program
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace Cosecutive  
 {  
   class ConsecutiveClass  
   {  
     static void Main(string[] args)  
     {  
       string s = "1-2-3-4-5-6";  
       List<string> numbers = s.Split('-').ToList();  
       int hyphenCount = s.ToCharArray().Count(x => x == '-');  
       int distinctNumCnt=numbers.Distinct().Count();  
       int listMaxLen = distinctNumCnt - 1;  
       int loopcount=0;  
       if ((hyphenCount + 1) == distinctNumCnt)  
       {  
         for (int i = 0; i < numbers.Count/2; i++)  
         {  
           if (Math.Abs(Convert.ToInt32(numbers[listMaxLen - i]) - Convert.ToInt32(numbers[i])) + 1 == distinctNumCnt)  
           {  
             distinctNumCnt -= 2;  
             loopcount++;  
           }  
           else  
           {  
             Console.WriteLine("Not Consecutive");  
             break;  
           }  
         }  
         if (loopcount == numbers.Count / 2)  
           Console.WriteLine("Consecutive");  
       }  
       else  
         Console.WriteLine("Not Consecutive");  
       Console.ReadLine();  
     }  
   }  
 }  


Test Case 1
Input :- "1-2-3-4-5"
O/p:




Test Case 2
Input :- "1-2-3-4-7"
O/p:


Thursday 14 July 2016

HashSet removing duplicates from custom class


Code
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace commongStringQuestion  
 {  
   class Program  
   {  
     class A :IEquatable<A>  
     {  
       public string Id { get; set; }  
       public string Name { get; set; }  
       public bool Equals(A other) {  
         return Id.Equals(other.Id) && Name.Equals(other.Name);  
       }  
       public override int GetHashCode()  
       {  
         return Id.GetHashCode();  
       }  
     }  
     static void Main(string[] args)  
     {  
       HashSet<A> obj = new HashSet<A>();  
       A obj3 = new A();  
       obj.Add(new A { Name = "A" ,Id= "1"});  
       obj.Add(new A { Name = "AB", Id = "1" });  
       obj.Add(new A { Name = "Abx", Id = "1" });  
       foreach (var item in obj)  
       {  
         Console.WriteLine(item.Name);  
       }  
       Console.WriteLine("===========================");  
       Console.ReadLine();  
     }  
   }  
 }  

Output







Adding same records now
   
using System; 
using System.Collections.Generic;   
 using System.Linq;  
 namespace LinqDetails  
 {  
   class Program  
   {  
     class A : IEquatable<A>  
     {  
       public string Id { get; set; }  
       public string Name { get; set; }  
       public bool Equals(A other)  
       {  
         return Id.Equals(other.Id) && Name.Equals(other.Name);  
       }  
       public override int GetHashCode()  
       {  
         return Id.GetHashCode();  
       }  
     }  
     static void Main(string[] args)  
     {  
       HashSet<A> obj = new HashSet<A>();  
       A obj3 = new A();  
       obj.Add(new A { Name = "A", Id = "1" });  
       obj.Add(new A { Name = "A", Id = "1" });  
       obj.Add(new A { Name = "A", Id = "1" });  
       foreach (var item in obj.OrderByDescending(x => x.Name))  
       {  
         Console.WriteLine(item.Name);  
       }  
       Console.WriteLine("===========================");  
       Console.ReadLine();  
     }   
   }  
 }   













UnionWith


 using System;   
  using System.Collections.Generic;   
  using System.Linq;  
 namespace LinqDetails  
 {  
   class Program  
   {  
     class A : IEquatable<A>  
     {  
       public string Id { get; set; }  
       public string Name { get; set; }  
       public bool Equals(A other)  
       {  
         return Id.Equals(other.Id) && Name.Equals(other.Name);  
       }  
       public override int GetHashCode()  
       {  
         return Id.GetHashCode();  
       }  
     }  
     static void Main(string[] args)  
     {  
       HashSet<A> obj = new HashSet<A>();  
       A obj3 = new A();  
       obj.Add(new A { Name = "A", Id = "1" });  
       obj.Add(new A { Name = "B", Id = "1" });  
       obj.Add(new A { Name = "C", Id = "1" });  
       HashSet<A> obj4 = new HashSet<A>();  
       obj4.Add(new A { Name = "C", Id = "1" });  
       obj4.Add(new A { Name = "D", Id = "1" });  
       obj4.UnionWith(obj);  
       foreach (var item in obj4.OrderByDescending(x => x.Name))  
       {  
         Console.WriteLine(item.Name);  
       }  
       Console.WriteLine("===========================");  
       Console.ReadLine();  
     }   
   }  
 }   











IntersectWith


 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace LinqDetails  
 {  
   class Program  
   {  
     class A : IEquatable<A>  
     {  
       public string Id { get; set; }  
       public string Name { get; set; }  
       public bool Equals(A other)  
       {  
         return Id.Equals(other.Id) && Name.Equals(other.Name);  
       }  
       public override int GetHashCode()  
       {  
         return Id.GetHashCode();  
       }  
     }  
     static void Main(string[] args)  
     {  
       HashSet<A> obj = new HashSet<A>();  
       A obj3 = new A();  
       obj.Add(new A { Name = "A" ,Id= "1"});  
       obj.Add(new A { Name = "B", Id = "1" });  
       obj.Add(new A { Name = "C", Id = "1" });  
       HashSet<A> obj4 = new HashSet<A>();  
       obj4.Add(new A { Name = "C", Id = "1" });  
       obj4.Add(new A { Name = "D", Id = "1" });  
       obj4.IntersectWith(obj);  
       foreach (var item in obj4.OrderByDescending(x => x.Name))  
       {  
         Console.WriteLine(item.Name);  
       }  
       Console.WriteLine("===========================");      
       Console.ReadLine();  
     }  
   }  
 }  



How to Get Property Names of a class


Code
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Reflection;  
 namespace commongStringQuestion  
 {  
   class Program  
   {  
     public class A  
     {  
       public string Name { get; set; }  
       public string Id { get; set; }  
       private string x { get; set; }  
     }  
     static void Main(string[] args)  
     {  
       A obja = new A();  
       obja.Id = "1";  
       obja.Name = "Anurag";  
       string value = "changed value";  
       foreach (var prop in obja.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))  
       {  
         Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obja, null));  
         prop.SetValue(obja, Convert.ChangeType(value, prop.PropertyType), null);  
       }  
       Console.WriteLine("-----------");  
       Console.WriteLine("Id : " + obja.Id);  
       Console.WriteLine("Name : " + obja.Name);  
       Console.ReadLine();  
     }  
   }  
 }  


Interview Question:- What will be the output of Default Integer Property ?


Case 1:

int x;
 Console.WriteLine(item);

o/p : Error
Reason: - Not initialized

Case 2:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace commongStringQuestion
{
    class Program
    {

        class A
        {

            public int Id { get; set; }
            public string Name { get; set; }

        }

        static void Main(string[] args)
        {
          
            HashSet<A> obj = new HashSet<A>();
            A obj3 = new A();
            Console.WriteLine(  obj3.Id);
            Console.ReadLine();
           
        }
    }
}

O/p :- 0


Case 3:- Can we initialize autoimplemented property

Yes in the constructor


class Cricket
{
    public Cricket()
    {
        PlayerName = "Sachin";
    }
    public string PlayerName { get; set; }

}


As of C#6 there is a new way:
public string PlayerName { get; set; } = "Sachin"


public string PlayerName { get; } = "Ganguly";

::-
other way is to get rid of auto implemented property and use normal property and assign the private fields in set.


Case 4:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace commongStringQuestion
{
    class Program
    {
        public class A
        {
            public string Name { get; set; }
            public string Id { get; set; }
            private string x { get; set; }
            private int counter;

            public A()
            {
                counter = 7;
            }
            public int Counter
            {
                get { return counter; }
            }
        }

        static void Main(string[] args)
        {
            A obja = new A();
           // obja.Counter = 8;//wrong
            Console.WriteLine(obja.Counter);
            Console.ReadLine();
        }
    }
}