Monday, 8 January 2018

Difference between == and Equals() in c#

Introduction

To compare equality between variables C# has provided two ways of doing comparison “==” and an overloaded method “equals()”. Most of the developers use “==” and “Equals” is hardly discussed.
So in this small note we will discuss about differences between them and when to use what.

Point 1 :- Comparison on the basis of Equality

Answering to the point “There is no difference between equality comparison using “==” and “Equals()”, except when you are comparing “String” comparison.
The common comparison Rule :-Whenever youare comparing variables they are either value types or reference types. When values types are compared they are compared on the basis of “Content” when reference types are compared they are compared on the basis of “Reference”(memory location) and not “Content”.
The above rule is respected by both “==” and “Equals”.

Scenario 1:- Value type comparison

When you compare value types / primitive data types ( int , double etc) either by using “==” or “Equals” it’s always based on content. In the below code you can see both comparison methods will show as “true”.
int i = 10;
int y = 10;
Console.WriteLine(i == y); // true
Console.WriteLine(i.Equals(y)); // true

Scenario 2:- Reference types comparison

Now when you compare objects they are compared on the basis of reference (internal memory pointer). Below obj and obj1 comparison either through “==” or “Equals” will be false. So in the below code even though both the object have property name as “Shiv” still it shows unequal. Because the comparison is based on internal memory reference which is different for “obj” and “obj1”.
Customerobj = newCustomer();
obj.Name = "Shiv";
Customer obj1 = newCustomer();
obj1.Name = "Shiv";
Console.WriteLine(obj == obj1); // false
Console.WriteLine(obj.Equals(obj1)); // false
But the below code will display true as the pointer points to same object.
Customerobj = newCustomer();
obj.Name = "Shiv";
Customer obj1 = obj;
Console.WriteLine(obj == obj1); // true
Console.WriteLine(obj.Equals(obj1)); // true

Scenario 3:- String comparison, interning and object type casting

Now strings are immutable objects or reference types so they should be checked using the rules of reference types. In other words in the below scenario when we assign value to “str” it creates a string object and in heap has “test” stored. When you now assign “str1” this a different object so it should be a different instance.
But look at the value, it the same. So C# string follows interning rule. In other words if the content is same “str” and “str1” they point to the same memory location and data. So both “==” and “Equals” will be true.
objectstr = "test";
object str1 = "test";
Console.WriteLine(str==str1);
Console.WriteLine(str.Equals(str1));
But now look at the below code where we are explicitly creating new separate objects of string with same value. We are forcing and overriding interning behavior of string.In the below code “==” will return false even though the content is same while “Equals” will return true. This is one place where the equality behavior differs.
objectstr = newstring(newchar[] { 't', 'e', 's', 't' });
object str1 = newstring(newchar[] { 't', 'e', 's', 't' });
Console.WriteLine(str==str1); // false
Console.WriteLine(str.Equals(str1));  // true

Point 2 :- Compile time VS RunTime

The next point which makes them different is when do type checks happen. “==” does type checking during compile time while “Equals” is more during runtime. You can see in the below code how “==” is showing a warning message with green sign saying that you are comparing different types and you can have issues. “Equals” does not show any such warnings.

Point 3 :- The NULL Situation

“==” works with nulls but “Equals” crashes when you compare NULL values , see the below print screen.


Sunday, 7 January 2018

What is extension method in c#

Extension method is that used to extend the existing class without modifying the structure of the class.

It can be achieved by static class with static member and using this keyword.

Example:

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

namespace ExtensionMethod
{
    public class ExtendClass
    {
        public void Display()
        {
            Console.WriteLine("Hi this is display method.");
        }
    }

    static class Program
    {
        public static void  NewDisplay(this ExtendClass cls)
        {
            Console.WriteLine("Hi this is new display method.");
        }

        static void Main(string[] args)
        {
            ExtendClass cls = new ExtendClass();
            cls.Display();
            cls.NewDisplay();
            Console.ReadLine();
        }
    }
}

What is Promises in Jquery



exp-

const money = 600;

const buyCar = new Promise(
 
  function(resolve,reject){
 
    if(money > 500){
      const car={
        Name:"Maruti",
        Year: "2015",
        Color:"White"
      }
      setTimeout(function(){
         resolve(car);
      },3000)
    }
    else{
      reject('Rejected due to not enogh amount');
    }
  }
)

//Handle multiple promises

const buyMultipleCars= [buyCar,buyCar,buyCar,buyCar,buyCar]
const cars = Promise.all(buyMultipleCars);
cars.
 then(function(data){
        console.log('success=>',data)
      }).
     catch(function(error){
       
         console.log('fail=>',error)
      });
     
//console.log(buyMultipleCars);

buyCar.
      then(function(data){
       console.log('success=>',data)
      }).
      catch(function(error){
        console.log('fail=>',error)
      });
        

Wednesday, 27 December 2017

Is c# support multiple inheritance?

No, c# does not support multiple inheritance of classes. To achieve multiple inheritance can go for Interface.

Exp -

public class A { }    
public class B { }
public class C { }
public class D { }
public class E { }

public interface IA { }
public interface IB { }
public interface ID{ }
public interface IE { }
C# does not support multiple inheritance of classes, but you are permitted to inherit/implement any number of interfaces.
This is illegal (B, C, D & E are all classes)
class A : B, C, D, E
{
}
This is legal (IB, IC, ID & IE are all interfaces)
class A : IB, IC, ID, IE
{
}
This is legal (B is a class, IC, ID & IE are interfaces)
class A : B, IC, ID, IE
{
}

Friday, 20 October 2017

Difference between filter() and find() method in Jquery

Both filter() and find() methods are very similar, except the former is applies to all the elements, while latter searches child elements only.
To simple
  1. filter() – search through all the elements.
  2. find() – search through all the child elements only.

jQuery filter() vs find() example

<html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
 div{
  padding:8px;
  border:1px solid;
 }
</style>

</head>

<body>

<h1>jQuery find() vs filter() example</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#filterClick").click(function () {

 $('div').css('background','white');

 $('div').filter('#Fruits').css('background','red');

    });

    $("#findClick").click(function () {

 $('div').css('background','white');

 $('div').find('#Fruits').css('background','red');

    });

  });
</script>
</head><body>

<div id="Fruits">
 Fruits
 <div id="Apple">Apple</div>
 <div id="Banana">Banana</div>
</div>

<div id="Category">
 Category
 <div id="Fruits">Fruits</div>
 <div id="Animals">Animals</div>
</div>

<br/>
<br/>
<br/>

<input type='button' value='filter(Fruits)' id='filterClick'>
<input type='button' value='find(Fruits)' id='findClick'>

</body>
</html>
OR,

find()  
     searches through all the child elements in the matched set.  

  Description:
          Get the descendants of each element in the current set of matched elements,  filtered by a selector.

  Syntax  
      .find( selector )
             selector: A string containing a selector expression to match elements against.

     .find( jQuery object )
           jQuery object: A jQuery object to match elements against.

     .find( element )
           element: An element to match elements against.

 filter()
      searches through all elements in the matched set.  

  Description:
        Reduce the set of matched elements to those that match the selector or pass the function's test.  

  Syntax 
     .filter( selector )
            selector: A string containing a selector expression to match the current set of elements against.

    .filter( function(index) )
           function(index): A function used as a test for each element in the set. this is the current DOM element.

    .filter( element )
          element: An element to match the current set of elements against.

    .filter( jQuery object )
         jQuery object:  An existing jQuery object to match the current set of elements against. 


Example 

<html>
     <head>
       <script src="jquery_1.7.1.min.js" type="text/javascript"></script>
       <script type="text/javascript">
          function filter_month(obj){
              jQuery('div').css('background','white');
               jQuery('div').filter(obj).css('background', '#83AFF8');
             }

         function find_month(obj){
             jQuery('div').css('background','white');
             jQuery('div').find(obj).css('background', '#83AFF8');
          }
       </script>
    </head>
    <body>   
       <div id="months">
          <table>
            <tr>
               <td> January </td>
               <td> February </td>
               <td> March </td>
               <td> April </td>
            </tr>
            <tr>
               <td> May </td>
               <td> June </td>
               <td> July </td>
               <td> August </td>
             </tr>
             <tr>
               <td> September </td>
               <td> October </td>
               <td> November </td>
               <td> December </td>
            </tr>
            </table>
       </div>
       <div> 
        <b> Category</b>
         <div id="months"> Month </div>
         <div id="weeks"> Weeks </div>
       </div>
       <input onclick = "filter_month('#months');" type = "button" value ="Filter" />
       <input onclick = "find_month('#months');" type = "button" value ="Find" />
   </body>
  </html>





JanuaryFebruaryMarchApril
MayJuneJulyAugust
SeptemberOctoberNovemberDecember

Category
Month
Weeks
   

Thursday, 14 September 2017

what is CSDL, SSDL and MSL sections in an EDMX file?

  • Conceptual Model(CSDL : Conceptual Schema Definition Language)
    The conceptual model contains the model classes and their relationships. This will be independent from the database table design.
  • Storage Model(SSDL : Storage Schema Definition Language)
    The storage model is the database design model which includes tables, views, stored procedures, relationships and keys.
  • Mapping (MSL : Mapping Schema Language)
    The mapping contains the information about how the conceptual model is mapped to storage model.