Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 3 May 2019

Write a single method which can be passed either any type of arrays and it returns the list of unique items in the specified list




1.    Consider the following two arrays:

string[] arrStrings = new string[] { “Bal”, “Yuriy”, “Ken”, “Apple”, “Ken” };
int[] arrNumbers = new int[] { 11, 2, 25, 34, 66, 25, 0, 0, 3, 4, 2, 89 };


Write a single method which can be passed either one of these arrays and it returns the list of unique items in the specified list. You cannot use LINQ to solve this problem.using System;


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arrStrings = new string[] { "Bal", "Yuriy", "Ken", "Apple", "Ken" };
            int[] arrNumbers = new int[] { 11, 2, 25, 34, 66, 25, 0, 0, 3, 4, 2, 89 };
            
            //For Integer arrays
            List<int> objIntList = new List<int>();
            objIntList = GetUniqueList<int>(arrNumbers);

            //For String arrays
            List<string> objStringList = new List<string>();
            objStringList = GetUniqueList<string>(arrStrings);
        }

    

        private static List<T> GetUniqueList<T>(T[] arraMix)
        {
            List<T> objUniqueList = new List<T>();
            foreach (var chkTest in arraMix)
            {
                if (!objUniqueList.Contains(chkTest))
                {
                    objUniqueList.Add(chkTest);
                }
            }
            return objUniqueList;
        }
    }
}















Tuesday, 21 August 2018

Find which word have more length form the given string "Anand Swaroop Upadhyay as df gh"



  string  temp=string.Empty;
            string strstring = "Anand Swaroop Upadhyay  as df gh";
            string [] strArray= strstring.Split(' ');
            foreach (var strvar in strArray)
            {
                if (string.IsNullOrEmpty(temp))
                {
                    temp = strvar;
                }
                else
                {
                    if (strvar.Length > temp.Length)
                    {
                        temp = strvar;
                    }

                }
            }
            Console.WriteLine(temp +"  is gretter");

            Console.Read();

i have a string like "anandaa" write a method or logic to get output like this a=4 n=2 d=1 means char count in string.




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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<char, int> objDict=new Dictionary<char,int>();
            string strStringName = "anandaa";
            char[] strchar = strStringName.ToCharArray();
            foreach (var charvalue in strchar)
            {
                int value=1 ;
                if (objDict.ContainsKey(charvalue))
                {
                    objDict.TryGetValue(charvalue, out value);
                    value++;
                    objDict[charvalue] = value;
                }
                else
                {
                    objDict.Add(charvalue, 1);
                }
            }

            foreach (KeyValuePair<char, int> kvp in objDict)
            {
             
                Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            }
            Console.Read();
        }
    }
}

Wednesday, 29 November 2017

Difference between var and dynamic in C#



Table of difference 



vardynamic
Introduced in C# 3.0
Introduced in C# 4.0
Statically typed – This means the type of variable declared is decided by the compiler at compile time.
Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
Need to initialize at the time of declaration.
e.g., var str=”I am a string”;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string.
No need to initialize at the time of declaration.
e.g., dynamic str; 
str=”I am a string”; //Works fine and compiles
str=2; //Works fine and compiles
Errors are caught at compile time.
Since the compiler knows about the type and the methods and properties of the type at the compile time itself
Errors are caught at runtime 
Since the compiler comes to about the type and the methods and properties of the type at the run time.
Visual Studio shows intellisense since the type of variable assigned is known to compiler.
Intellisense is not available since the type and its related methods and properties can be known at run time only

e.g., var obj1;
will  throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.
e.g., dynamic obj1; 
will compile;
e.g. var obj1=1;
will compile 
var obj1=” I am a string”;
will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety.
e.g. dynamic obj1=1;
will compile and run 
dynamic obj1=” I am a string”; 
will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value “I am a string” was assigned to it.
This code will work fine. 

Tuesday, 21 November 2017

Singleton Vs Static Classes in details.


Understanding Protected, Internal and Protected Internal Access modifiers in OOPs in details

Concept 

First of all Let us remember the exact definitions of them as per various sources.
1.       Protected: The type or member can only be accessed by code in the same class or struct, or in a derived class.
2.       Internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.
3.      Protected Internal The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
Quite easy .. Right! Yes, of course. 

Understanding and coding

Let us take an example in C#. Please refer the below code at the same time.
·         Create a Console Application/ Project in C#.
·         Create Two Separate assemblies named like ‘Assembly_1’ and ‘Assembly_2’.
·         Now we will write code in the first assembly i.e. ‘Assembly_1’.
·         Write two normal Class named ‘Soul’ and ‘Soul_1’.
·         Now inside class ‘Soul’ , create four different classes ‘A’ ,’B’,’C’ and ‘G’. Here classes ‘A’ ,’B’ and ’C’ contains different access-modifiers! Noticed!!! But not class ‘G’ which is by default internal.
·         Write some static public functions like fnA()fnB()’ ,‘fnC()’ and ‘fnG()’ having some simple output messageslike below in the code.
·         Now try calling all there functions one-by-one inside class ‘G’ like
                A.fnA();
                B.fnB();
                C.fnC();
                Console.WriteLine("fnG");
·         What do we find??? The class ‘G’ is inside the same class 'Soul' so everything is accessible from above. Does not consider a modified indeed. Hurray!!
·         Now the Next step. Try calling the same code inside class ‘Soul_1’.
·         What do we find??? This class is NOT in same class 'Soul' but in the same assembly ‘Assembly_1’ so  only protected is NOT accessible rest all are accessible. If you want to access protected then need to inherit class 'Soul'.
·         Wow that was great!
·         Now we will move to another assembly named ‘Assembly_2’.
·         Write a class ‘KISH’ and inherit previous class Soul from Assembly_1 like

 class KISH : Assembly_1.Soul
{…}
·         Last but not the least create a class ‘D’ and call the above methods
       Console.WriteLine("fnD");
             A.fnA();
             B.fnB();
             C.fnC();
What do we find??? If it does not inherit class 'Assembly_1.Soul' then we cannot access anything because this is 'ANOTHER' assembly .  Hence, only INTERNAL is NOT accessible , rest all are accessible from first assembly if it inherits class 'Soul'.

Please refer the code below:
namespace Assembly_1 //This is first assembly.
{
    //A normal public class which contains all different types of access-modifier classes in the assembly named 'Assembly_1'
    public class Soul              
    {
        //protected class A
        protected class A
        {
            public static void fnA()
            {
                Console.WriteLine("fnA");
            }
        }
       
        //internal class
        internal class B
        {
            public static void fnB()
            {
                Console.WriteLine("fnB");
            }
        }

        //protected internal
        protected internal class C
        {
            public static void fnC()
            {
                Console.WriteLine("fnC");
            }
        }

        //TIP 1:This class is inside the same class 'Soul' so everything is accessible from above.Hurray!!
        class G                       
        {
            public static void fnG()
            {
                //All methods are easily accessible.Does not consider a modified indeed.
                A.fnA();
                B.fnB();
                C.fnC();
                Console.WriteLine("fnG");
            }
        }
    }

    //Different class but inside the same assembly named 'Assembly_1'
    public class Soul_1
    {
        //Accesibility of 'protected members'::NO
        //Accesibility of 'internal members'::YES
        //Accesibility of 'protected internal' members::YES
        //TIP 2:This class is NOT in same class 'Soul' but in the same assembly so  only protected is NOT accessible rest all are accessible.
        //IF you want to access protected then inherit class 'Soul'.
        public void fnSoul_1()
        {
            //Soul.A.fnA();//ERROR:Accesibility of 'protected'::NO.ONLY WHEN Soul_1:Soul i.e. when Soul_1 inherits Soul.
            Soul.B.fnB();
            Soul.C.fnC();
            Console.WriteLine("fnSoul_1");
        }
    }
}

namespace Assembly_2 //This is second assembly.
{
    //TIP:if it does not inherit class 'Soul' then we can not access any thing beacuse this 'ANOTHER' assembly.
    //TIP:only INTERNAL is NOT accessible , rest all are accessible from first assembly if it inherits class 'Soul'
    class KISH : Assembly_1.Soul
    {
        //=======================================================================
        class D
        {
            void fnD()
            {
                //
                Console.WriteLine("fnD");
                A.fnA();//YES, becuase this is 'protected'
                //B.fnB();//ERROR:NO, becuase this is 'internal':TIPS 3:only internal is not accessible.
                C.fnC();//YES, becuase this is 'protected internal'
            }
        }
    }
}

Conclusion

Here is a Short and simple Matrix to memorise the above concept.
Accessbility Matix to RememberSame AssemblyDifferent Assembly
Access Modifer TypeShort NameSame ClassDifferent ClassAny class(inherits previous assembly class)
ProtectedPYesNoYes
InternalIYesYesNo
Protected InternalPIYesYesYes


Hope it will help you to crack OOP's concept .Cheers!!

Anand Upadhyay