Friday, August 9, 2019

C# - Dynamic Type

C# 4.0 (.NET 4.5) introduced a new type that avoids compile time type checking,  it resolves type at run time.
dynamic myStr= "Ram";

myStr++;  // it wont give any error but when we run then it will through error.

Console.WriteLine(myStr.GetType().ToString());

A dynamic type changes its type at runtime based on the value of the expression to the right of the "=" operator.

dynamic myStr= 100; Console.WriteLine("Dynamic variable value: {0}, Type: {1}",myStr,
myStr.GetType().ToString()); 

compiler would not check for correct methods and properties name of a dynamic type therefore it will allow to write the method name which is actually not there in class. It will throw error at run time.

A method can have dynamic type parameters so that it can accept any type of parameter at run time. 
class Program { static void PrintValue(dynamic val) { Console.WriteLine(val); } static void Main(string[] args) { PrintValue("Hello World!!"); PrintValue(100); PrintValue(100.50); PrintValue(true); PrintValue(DateTime.Now); } }


Points to Remember :

  1. The dynamic types are resolved at runtime instead of compile time.
  2. The compiler skips the type checking for dynamic type. So it doesn't give any error about dynamic types at compile time.
  3. The dynamic types do not have intellisense support in visual studio.
  4. A method can have parameters of the dynamic type.
  5. An exception is thrown at runtime if a method or property is not compatible. 

 

C# indexers

C# indexers are usually known as smart arrays. A C# indexer is a class property that allows you to access a member variable of a class or struct using the features of an array. In C#, indexers are created using this keyword. Indexers in C# are applicable on both classes and structs. 
Instances of that class can be accessed using the [] array access operator.

Important points to remember on indexers: 

  • Indexers are always created with this keyword.
  • Parameterized property are called indexer.
  • Indexers are implemented through get and set accessors for the [ ] operator.
  • ref and out parameter modifiers are not permitted in indexer.
  • The formal parameter list of an indexer corresponds to that of a method and at least one parameter should be specified.
  • Indexer is an instance member so can't be static but property can be static.
  • Indexers are used on group of elements.
  • Indexer is identified by its signature where as a property is identified it's name.
  • Indexers are accessed using indexes where as properties are accessed by names.
  • Indexer can be overloaded.

Indexer are defined in pretty much same way as properties, with get and set functions. The main difference is that the name of the indexer is the keyword this.

Difference between Indexers and Properties

Indexers
Properties
Indexers are created with this keyword.
Properties don't require this keyword.
Indexers are identified by signature.
Properties are identified by their names.
Indexers are accessed using indexes.
Properties are accessed by their names.
Indexer are instance member, so can't be static.
Properties can be static as well as instance members.
A get accessor of an indexer has the same formal parameter list as the indexer.
A get accessor of a property has no parameters.
A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.
A set accessor of a property contains the implicit value parameter.


Indexers are commonly used for classes, which represents some data structure, an array, list, map and so on.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
    public class Customer
    {
        private List<Address> Addresses = new List<Address>();
        public Customer()
        {
            Addresses.Add(new Address { Pincode = 110059, Mobile = "9999999999" });
            Addresses.Add(new Address{ Pincode = 110064, Mobile = "8888888888" });
        }
        public Address GetAddress(int Pincode)
        {
            foreach (var item in Addresses)
            {
                if (item.Pincode == Pincode) return item;
            }
            return null;
        }
        //Indexer property
        public Address this[int Pincode]
        {
            get
            {
                foreach (var item in Addresses)
                {
                    if (item.Pincode == Pincode) return item;
                }
                return null;
            }
        }
    }
    public class Address
    {
        public int Pincode { get; set; }
        public string Mobile { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer();
            //Address addr= cust.GetAddress(110059);  //calling the method through class object
            Address addr = cust[110059];  // we have used indexer on class itself instead of calling the properties through class object
            Console.WriteLine(addr.Mobile);
            Console.ReadKey();

        }
    }
}

Thursday, August 8, 2019

Operator overloadin in C#


// C# program to illustrate the
// Binary Operator Overloading 
using System;
namespace BinaryOverload
{
    class Calculator
    {
        public int number = 0;
        // no-argument constructor
        public Calculator() { }

        // parameterized constructor
        public Calculator(int n)
        {
            number = n;
        }
        // Overloading of Binary "+" operator
        public static Calculator operator +(Calculator Calc1,
                                             Calculator Calc2)
        {
            Calculator Calc3 = new Calculator(0);
            Calc3.number = Calc2.number + Calc1.number;
            return Calc3;
        }
        // function to display result
        public void display()
        {
            Console.WriteLine("{0}", number);
        }
    }

    class CalNum
    {
        // Driver Code
        static void Main(string[] args)
        {
            Calculator num1 = new Calculator(200);
            Calculator num2 = new Calculator(40);
            Calculator num3 = new Calculator();

            num3 = num1 + num2;
            num1.display(); // Displays 200
            num2.display(); // Displays 40
            num3.display(); // Displays 240
            Console.ReadKey();
        }
    }
}

Constructor callin in inheritance in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{//Base class
    class Base
    {
        public Base(){ Console.WriteLine("Constructor: Base"); }
    }
    //Derived class
    class DerivedOne : Base
    {
        public DerivedOne(){ Console.WriteLine("Constructor: DerivedOne"); }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Base o = new DerivedOne();
            Console.ReadKey();
        }
    }
}

Output:
Constructor: Base
Constructor: DerivedOne

Friday, August 2, 2019

IP Address Is Not Allowed to Access Server in Azure Database Connection

When using SQL databases on Azure, the firewall on the DB server blocks requests from unknown IPs. This means that when you try to connect from a client such as SQL Server Management Studio (SSMS) or Visual Studio, your request to connect to the DB is rejected with the following message:

Cannot connect to *******.database.windows.net.

Cannot open server ‘*******b’ requested by the login. Client with IP address ‘*********’ is not allowed to access the server.  To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range.  It may take up to five minutes for this change to take effect. (Microsoft SQL Server, Error: 40615)

image

What you need to do is configure the firewall on the Azure Database Server to allow a connection from your local IP address. Follow these steps:

1. Go to the Azure Portal and navigate to your database.

2. On the blade for your database, click the link to the DB server on the upper right corner.

image

3. Once you are on your DB server's blade, click “Firewall” from the options on the left-hand side.

image

4. On the firewall blade, click the “Add client IP” button on the top. This adds your current IP address to the rule list. Don’t forget to give it a meaningful name in order to be able to remove it later. (If you don’t need it anymore).

image

5. Click “Save”

Note that it can take several minutes even AFTER the setting changes are confirmed in the portal for you to be able to log into your database.