Menu Close

Author: uk365guy

ACCESS MODIFIERS FOR TYPES(CLASSES) IN C#

CLASSES, STRUCTURES, INTERFACES, DELEGATES WILL HAVE TYPES AND CAN ONLY USE INTERNAL OR PUBLIC ACCESS MODIFIERS

using System;
namespace ConsoleApplication4
{
    public class AssemblyOne
    {
        public void PrinID()
        {
            Console.WriteLine(“print this is a types example”);
        }
    }
}
// default  is internal for type classes like classes, structures, interfaces, delegates, etc..
// default  is private for type members like fields, properties, methods, etc 
using System;
using AssemblyOne;
namespace ConsoleApplication4
{
internal class AssemblyTwo 
    {
        AssemblyOne instance = new AssemblyOne();
        instance.xxxxxx     = xyz;
    }
}
Share this:

ACCESS MODIFIERS IN C#

ACCESS MODIFIERS IN C#

Types Vs Type Members


In C# there are 5 different access modifiers in c#
1.Private
2.Protected
3.Internal
4. Protected Internal
5. Public

Private members are available only with in the containing type, where as public members are available any where. There is no restricction.

Protected Members are available, with in the containing type and to the types that derive from the containing type

Access Modifier                       Accessibility
Private ->                  Only with in the containing class
Public ->                  Any where, No Restrictions
Protected ->                 With in the containing types and the types derived from the
                                                 containing type.
————————————————————————————————————————-

using System;
using System.IO;

namespace ConsoleApplication4
{

    //public class Customer
    //{

    //    private int _id;

    //    public int Id
    //    {
    //        get { return _id; }
    //        set { _id = value; }

    //    }
    //}

    public class Customer
    {
        protected int _id;
    }

    public class corporateCustomer : Customer
    {
        public void printID()
        {
            corporateCustomer cc = new corporateCustomer();
            cc._id = 101;
        }
    }

   public  class Program
    {
        public static void Main()
    {
        Customer C1 = new Customer();
        Console.WriteLine(C1._id);
    }

    }
}
————————————————————————————————————————-

INTERNAL AND PROTECTED INTERNAL ACCESS MODIFIERS IN C#


INTERNAL AND PROTECTED INTERNAL
A member with internal access modifier is available anywhere with in the containing assembly. it’s a compile time error to access, an internal member from outside the containing assembly.
Protected Internal members can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. It is a combination of protected and internal. If you have understood protected and internal, this should be very easy to follow. 



Access Modifier                       Accessibility
Private                    Only with in the containing class
Public                   Any where, No Restrictions
Protected                   With in the containing types and the types derived from the 
                                                 containing type.
Internal                  Anywhere with in the containing assembly
ProtectedInternal         Anywhere with in the containing assembly, and from within a 

                                                 derived class in any another assembly.



INTERNAL:- 

Internal fields are accessible within the assembly where it is defined not outside of the assembly.
PROTECTED INTERNAL:-
Protected Internal are accessible within the assembly and in the derived class through inheritance within another assembly(refering the base class in the derived class through reference or namespace declaration).

Share this:

UNDERSTANDING DIFFERENCE BETWEEN TYPES AND TYPE MEMBERS IN C#

DIFFERENCE BETWEEN TYPES AND TYPE MEMBERS IN C#

Types Vs Type Members

In this example Customer is the Type and fields, properties and method are type members.

So, in general classes, structs, enums, interfaces, delegates are called as types and fields, properties, constructors, methods etc.. that normally reside in a type are called  as type members.

In C# there are 5 different access modifiers:
1.Private
2.Protected
3.Internal
4. Protected Internal
5. Public

Type members can have all the access modifiers, where as types can have only 2 (internal , public) of the 5 access modifiers

Note: Using regions you can expand and collapse sections of your code either manually, or using visual studio Edit>Outling > Toggle All Outlining

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {

        }

    }

    public class Customer
    { 
        #region fields
        private int _id;
        private string _firstName;
        private string _lastName;
        #endregion

        #region properties
        public int Id
        {
            get { return _id; }
            set { _id = value; }

        }
        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }

        }
        public string LastName
        {
            get { return _lastName;}
            set { _lastName = value; }
        }
        #endregion

        #region methods
        public string GetFullName()
        {
            return this.FirstName + ” ” + this.LastName;
        }
        #endregion


    }
}

Share this:

ENUMS IN C#

WHY ENUMS

Enums are strongly typed constants

If a program uses set of integral numbers, consider replacing them with enums. otherwise the program becomes less
 > Readable
 > Maintainable

———————————————————————————————————————–

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            Customer[] customers = new Customer[3];

            customers[0] = new Customer
            {
                Name = “Malla”,
                Gender = 1
            };
            customers[1] = new Customer
            {
                Name = “mary”,
                Gender = 2

            };
            customers[2] = new Customer
            {
                Name = “hyyjjj”,
                Gender = 0
            };

            foreach (Customer customer in customers)
            {
                Console.WriteLine(“Name = {0} && Gender = {1}”, customer.Name, GetGender(customer.Gender));
                Console.ReadLine();
            }

        }

        public static string GetGender(int gender)
        {
            switch(gender)
            {
//      INTEGRAL NUMBERS BESIDE CASES SHOULD BE REPLACES WITH ENUMS TO //BETTER READABLE
                case 0:
                    return “Unknown”;
                case 1:
                    return “Male”;
                case 2: 
                    return “Female”;
                default:
                    return “Invalid data detected”;
            }
    }
        //0 Unknown
        //1  Male
        //2 Female

        public class Customer
        {
            public string Name { get; set; }
            public int Gender { get; set; }
        }
    }
}
————————————————————————————————————————

USE ENUMS FOR THE ABOVE PROGRAM MORE READABLE


using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            Customer[] customers = new Customer[3];

            customers[0] = new Customer
            {
                Name = “Malla”,
                Gender = Gender.Male
            };
            customers[1] = new Customer
            {
                Name = “mary”,
                Gender = Gender.Female

            };
            customers[2] = new Customer
            {
                Name = “hyyjjj”,
                Gender = Gender.Unknown
            };

            foreach (Customer customer in customers)
            {
                Console.WriteLine(“Name = {0} && Gender = {1}”, customer.Name, GetGender(customer.Gender));
                Console.ReadLine();
            }

        }

        public static string GetGender(Gender gender)
        {
            switch(gender)
            {
                case Gender.Unknown:
                    return “Unknown”;
                case Gender.Male:
                    return “Male”;
                case Gender.Female: 
                    return “Female”;
                default:
                    return “Invalid data detected”;
            }
    }
        //0 Unknown
        //1  Male
        //2 Female
        public enum Gender
        {
            Unknown,
            Male,
            Female
        };

        public class Customer
        {
            public string Name { get; set; }
            public Gender Gender { get; set; }
        }
    }
}


 ————————————————————————————————————————-
ENUMS USAGE


If a program uses set of integral numbers, consider replacing them with enums. otherwise the program becomes less
 > Readable
 > Maintainable

1.Enums are enumerations
2.Enums are strongly typed constants, Hence, an explicit cast is needed to convert from enum type to an integral type and vice versa.Also an enum of one type cannot be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
3. The default underlying type of an enum is int.
4.The default value for firt element is zero and gets incremently by 1.
5 it is possible to customize the underlying type and values.
6. Enums are value types.

7. Enum keyword (all small letters) is used to create enumerations. where as Enum class, contains staticGetValues() and GetNames() methods which can be used to list Enum underlying type values and Names.

Enum(with capital Eis a class)

enum (with small e is to create enumerations)

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            short[] Values = (short[])Enum.GetValues(typeof(Gender));

            foreach (int value in Values)
            {
                Console.WriteLine(value);     
            }
            string[] Names = Enum.GetNames(typeof(Gender));

            foreach (string name in Names)
            {
                Console.WriteLine(name);
                Console.ReadLine();
            }
       
    }
        //0 Unknown
        //1  Male
        //2 Female
       
        public enum Gender : short
        {
            Unknown = 1,
            Male = 5,
            Female = 23
        };

        public class Customer
        {
            public string Name { get; set; }
            public Gender Gender { get; set; }
        }
    }
}

Share this:

EXCEPTION ABUSE AND HOW TO RESOLVE IN C#

Exception Handling abuse


Exceptions are unforseen errors that occur when a program is running. For example, when an application is executing a query, the database connection is lost, Exception is generally used to handle scenarios.


Using exception handling to implement program logical flow is bad and is termed as exception handling abuse.

————————————————————————————————————————
using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            try
            {
                Console.WriteLine(“Please enter Numarator”);
                int Numarator = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine(“Please enter Denaminator”);
                int Denaminator = Convert.ToInt32(Console.ReadLine());

                int Result = Numarator / Denaminator;

                Console.WriteLine(“Result = {0}”, Result);
                Console.ReadLine();
            }
            catch(FormatException)
            {
                Console.WriteLine(“Please enter valid number “);
                Console.ReadLine();
            }
            catch(OverflowException)
            {
                Console.WriteLine(“Only numbers beteen {0} && {1}”, Int32.MinValue, Int32.MaxValue);
                Console.ReadLine();
            }
            catch(DivideByZeroException)
            {
                Console.WriteLine(“Denominator cannot be Zero”);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
    }
}
=======================================================================

EXCEPTION HANDLING ABUSE RESOLVED..

CORRECT WAY TO USE EXCEPTION HANDLING AFTER VALIDATION


using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            try
            {
                Console.WriteLine(“Please enter Numarator”);
                int Numarator;
                bool IsNumaratorConversionSuccessful = Int32.TryParse((Console.ReadLine()), out Numarator);

                if (IsNumaratorConversionSuccessful)
                {
                    Console.WriteLine(“Please enter Denominator”);
                    int Denominator;
                    bool IsDenominatorConversionSuccessful = Int32.TryParse((Console.ReadLine()), out Denominator);

                    if (IsDenominatorConversionSuccessful && Denominator != 0)
                    {
                        int Result = Numarator / Denominator;

                        Console.WriteLine(“Result = {0}”, Result);
                        Console.ReadLine();
                    }
                    else
                    {
                        if (Denominator == 0)
                        {
                            Console.WriteLine(“Denominator cannot be Zero”);
                            Console.ReadLine();
                        }
                        else
                        {
                            Console.WriteLine(“Denominator should be valid number between {0} && {1}”, Int32.MinValue, Int32.MaxValue);
                            Console.ReadLine();
                        }
                    }

                }
                else
                {
                    Console.WriteLine(“Numarator should be valid number between {0} && {1}”, Int32.MinValue, Int32.MaxValue);
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}


Share this: