Thursday, December 28, 2017

Difference Between ItemPanel and ItemTemplate

 ItemsSource="{Binding}">
  
    
       Background="SteelBlue" Padding="5" BorderBrush="Black"
        BorderThickness="1" Margin="0,2">
         Text="{Binding}"/>
      
    
Background="DarkKhaki"/>
And the result:
WPF ListBox templates example
The ItemTemplate determines the layout of each item in the list. On the other hand the ItemsPanel is the panel that will contain the individual items. Given the above definition the visual tree will be something similar to this:

Difference between * and Auto

"*" means stretch to fill the available space, and is a fraction, so if one row is * and the other row is 2* then the second row will be twice the size of the first row.
Auto means it takes whatever/or only space it needs.
 <Grid>
  <Grid.RowDefinitions>
   <RowDefinition Height="*"/>
   <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>

  <Button Content="Test" Grid.Row="1" />

 </Grid>
So for example, you may have two rows, bottom row has a button and is Auto (only as high as the button) and the top row is "*" - stretches to the remaining space available.

GRASP


  • Acronym for General Responsibility Assignment Software Pattern
  • Appropriate assignment of responsibility to classes is the key of success in a project.
  • There are fundamental principle in assigning responsibilities they are summarized in GRASP.
  • There are nine principle that object oriented designer apply.
9 GRASP patterns

1. Creator
2. Information Expert
3. Low Coupling
4. Controller
5. High Cohesion
6. Indirection
7. Polymorphism
8. Protected Variations
9. Pure Fabrication

1. Creator : Who creates an object. Container object creates contained object. Decide who can be creator based on interaction and association of object.
Example : Video Store is container and video is contained object. Video Store has an Aggregation relationship with Video. so we can instantiate video object inside Video Store class.

2. Expert : 

What responsibility should assign to object. Expert Principle says give the responsibility to object for which it has the information to full fill the responsibility. Or in some cases they colloborate with other to get the information.

Example :
Assume we need to get all videos of a video store. Since Video store has all the information required for this task so we can assign this responsibility to video store.

class VideoStore
{
getAllVideos();

}


3. Low Coupling

Object should be loosely coupled.

Two elements are coupled if
1. One element has aggregation/composition relationship with another element.
2. One element implements another.

Example of Poor Coupling




4. Controller

Deals with how to delegate the request from UI layer to domain layer object
Controller decide who will process this request.
This object is called controller which receive the request from UI.


We can make an object controller if

1. Object represent the overall system (facade controller)
2. Object represent a use case, handling a sequence of operation (session controller)


Benefit
1. Can reuse this controller class
2. Can control the sequence of operations.


Blotted Controller

Controller class is called blotted if it is overloaded with too many responsibilities.
Solution : Add more controller

Controller class also performing many task other than delegation.
Solution : Controller class has to delegates things to others


5. High Cohesion

  • How are the operations of an element are functionally related?
  • Related responsibilities should be be in one manageable unit
  • Prefer High Cohesion
  • Clearly define the purpose of an element.
  • Benefits
    • Easily understandable and maintainable
    • Code reuse
    • Low coupling 





6. Polymorphism

  • How to handle related and varying elements based on element type?
  • Polymorphism guides us in deciding which object is responsible for handling those varying elements.
  • Benefit : Handling new variations becomes easy.

7. Pure Fabrication


Fabricated class/ artificial class – assign set of related responsibilities that doesn't represent
any domain object.

● Provides a highly cohesive set of activities.
● Behavioral decomposed – implements some algorithm.
● Examples: Adapter, Strategy
● Benefits: High cohesion, low coupling and can reuse this class.


Example If we want to store shape data in database and write this functionality inside shape class then there will be need to write some database related operation inside shape class which will make it incohesive So solution is that create a separate DBStore class for storing.

Similarly Logging interface which write log it is an good example of Pure Fabrication

8. Indirection

  • How can we avoid direct coupling between two or more elements?
  • Indirection introduce an intermediate unit to facilitate their communication so that they will not be directly coupled.
  • Benefit : Low Couplinng
  • Example : Facade, Observer, Adaptor

9. Protected Variation/ Don't talk to Strangers

  • How to avoid impact of variation of some element on other elements?
  • It defines a well defined interface so that there will be no affect on other elements.
  • Provides flexibility and protection from variations.
  • Provide more structured design
  • Example : Polymorphism,Data Encapsulation and interfaces

Friday, December 22, 2017

GetHashCode() Method

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality........................from MSDN

If two object are equal than their hascode will be same but reverse is not true means if hashcode is same for than object may be different.


https://blogs.msdn.microsoft.com/ericlippert/2011/02/28/guidelines-and-rules-for-gethashcode/

Overriding Equals

When you override Equal method in .Net it gives you warning that you have not override GetHashCode method.

class PhoneNumber
    {
        public String AreaCode { get; set; } = "2";
         public String Exchange { get; set; } = "45";

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;

            var phoneNum = obj as PhoneNumber;

            return this.AreaCode == phoneNum.AreaCode && this.Exchange == phoneNum.Exchange;
           
        }
    }

Although it is fine works well.

So Why .Net asking for overriding GetHashCode method let see

Suppose we have added our object in dictionary

Dictionary directory = new Dictionary();

directory.Add(
    new PhoneNumber { AreaCode = "123", Exchange = "456" },
    new Employee { FirstName = "Gordon", LastName = "Freeman" });

directory.Add(
    new PhoneNumber { AreaCode = "111", Exchange = "222" },
    new Employee { FirstName = "Gordon", LastName = "Freeman" });
    );

Lets try to pull our value


Employee employee = directory[new PhoneNumber { AreaCode = "123", Exchange = "456"}];
// Throws exception: "The given key was not present in the dictionary"


Also it would not throw an error while you will add same value object

Dictionary directory = new Dictionary();

directory.Add(
    new PhoneNumber { AreaCode = "123", Exchange = "456" },
    new Employee { FirstName = "Super", LastName = "Mario" });

directory.Add(
    new PhoneNumber { AreaCode = "123", Exchange = "456"},
    new Employee { FirstName = "Princess", LastName = "Peach" });

// No duplicate key exceptions thrown!


What is the Correct way to do that

Dictionary directory = new Dictionary();

PhoneNumber number = new PhoneNumber { AreaCode = "123", Exchange = "456"};

directory.Add(number, new Employee { FirstName = "Super", LastName = "Mario" });

Employee employee = directory[number]; // Works!

As these examples demonstrate, the Dictionary uses GetHashCode to quickly pull up a set of results from the collection. Once it has this set, then it can go through each one and verify equality by using Equals; calling Equals on a small set retrieved via a hash-based search is a lot more efficient than calling Equals on the whole lot.

If we haven’t implemented our own version of GetHashCode, then the default implementation of the method is used, which generates a hash specific to the instance of the object itself, rather than a hash based on the values within our class. To be able to properly use our PhoneNumber in a hash-based collections, we need the latter.

(You’ll note that this is analogous to how the default, reference equality implementation of Equals differs from our overridden, value equality implementation above)

Now that we’re convinced we need to override GetHashCode, let’s do it:

Override GetHashCode()

Here’s the golden rule for implementing GetHashCode (from MSDN):

If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

Based on that, we can surmise that the properties of the class used in our implementation of Equals should make a reappearance in our implementation of GetHashCode. On top of that, we know that we need to return an int from GetHashCode.

Furthermore, because GetHashCode will be used to find objects within hash-based collections, our implementation of GetHashCode should meet two other qualifications: quick to compute with a relatively unique result.

If we have an implementation of GetHashCode that takes a long time, then we will severely impact the performance of any hash-based collection that uses our class.

Furthermore, recall from above that hash-based collections first use GetHashCode to get a smaller subset of items from a collection and then look through those objects with Equals. If our implementation often generates similar hashes, this will cause “collisions” (essentially, similar or identical hashes crowded together) in our hash-based collections, forcing these collections to constantly rifle through a large set of results from a GetHashCode search.

public override int GetHashCode()
{
    int hash = 13;
    hash = (hash * 7) + AreaCode.GetHashCode();
    hash = (hash * 7) + Exchange.GetHashCode();
    hash = (hash * 7) + SubscriberNumber.GetHashCode();
    return hash;
}


How did we end up with 7 and 13? Well, we were looking for prime numbers as this ensures our hash will produce evenly distributed numbers

To make it more accurate so that it can throw exception in case of overflow

public override int GetHashCode()
{
     unchecked
    {
        int hash = 13;
        hash = (hash * 7) + (!Object.ReferenceEquals(null, AreaCode) ? AreaCode.GetHashCode() : 0);
        hash = (hash * 7) + (!Object.ReferenceEquals(null, Exchange) ? Exchange.GetHashCode() : 0);
        hash = (hash * 7) + (!Object.ReferenceEquals(null, SubscriberNumber) ? SubscriberNumber.GetHashCode() : 0);
        return hash;
    }
}

http://www.loganfranken.com/blog/692/overriding-equals-in-c-part-2/

Wednesday, December 20, 2017

RPA

1. What is RPA?
RPA stand for Robotic Process Automation. that is automation of some process which has fixed rules and regulation. Suppose a user daily doing  data entry from excel to database, It can be automated with the help of RPA.

2. Why RPA?
Ans . It saves cost
2. More accurate in less time.
3. Easy to implement and learn.
4. Fast than normal user.

3. How many tools are available for RPA?
Ans. 1. UI Path -- community edition is free for individual
2. Blue Prism
3. Automation Anywhere?
4. Work Fusion

CPA Global

1. What is DLR?
2. Difference between DLR and CLR?
3. Which one process the dynamic variable DLR or CLR?
4. static dynamic variable handled by?
5. What is abstraction?
6. What is Encapsulation?
7. Difference between both above?
8. What is static?
9. Which pattern you have ussed?
10. What is Singleton?
11. What is trigger?
12. Difference between Procedure and Function.
13. What is BSON Format?
14. What is return of Mongo DB?
15. Difference Between Mongo and SQL
16. What are Http Verb?
17 Differnece between put and post.
18. How static object disposed?

How to do Session Management in Web API
Model Binding in Web API
How many verbs and what are supported in web API


Shared by Noor

Monday, December 18, 2017

Infogain

What is provider ?
What is factory. how to implement.
What is service how to use services in angular js
What is directive. how to use custom directive. 
default directive restriction
isolation 
difference between factory and service
how to prevent to show expression brackets {{}} on loading.
$q service and its implementation
How to do Session Management in Web API
Model Binding in Web API
How to do Session Management in Web API
Model Binding in Web API
How many verbs and what are supported in web API

Shared By Noor

Saturday, December 16, 2017

Saxo Bank

What is shallow copy and deep copy?
2. How can we make deep copy?
3. If there are two threads one filling the queue and other one is consuming the queue. First one wait if queue is full second wait if queue is empty. Write the sudo code.
4. Write a program so that every user get updated value on their screen when some one update.
5. Which is fast 'in' and 'not in'?
6. How can we replace 'not in' something which is fast?
Ans : using inner join

7. If there is a grid which is fetch data from database is there any mechanism to push data into grid from database.
8. Design an application where every user screen changed when any user add some value.
9. What other methods need to override while overriding Equal method and why?
10. What is the benefit of xml serialization?
11. What is advantage of implementing IDisposable interface other than dispose method called while using in using statement.
12. What is race condition?

Thursday, December 14, 2017

Exl Services

Singleton Pattern?
How will you use singleton pattern in multithreading environment?
What is Mutex?
Explain SOLID principle?
Any Implementat of SOLID principle in your project?
Difference between factory method and abstract factory? give some real example?
What are the process of NUnit test?
What is the role of technical architect?
What is Async and Await?
How to pass results in multiple tasks?
WCF Vs WebApi?
What are the contracts in WCF?
Any performance monitoring tool that you have used for your application?
What steps you will take if Stored procedure is fast in development environment and slow in production environment?
What is .NET CORE?

Angular 2

1. What is Angular 2

Angular 2 is a JavaScript framework which allows to create reactive Single Page Application.

2. What is Angular CLI

Ans : A command line interface for Angular

Command to install Angular CLI :-npm install -g @angular/cli

* CLI uses Webpack  a tool which bundles all css and JS and include them in index.html file.

If you face any error installing any component from npm than run below command

npm set strict-ssl false

3. What are Directives?
Ans. Directives are instruction to DOM to do some action.

Or

A directive is a custom HTML element that is used to extend the power of HTML.

4. What are the types of directive?
Ans. There are two types of directives one is structure directive and other is attribute directive?

Structure directive add or remove the element in DOM. Example is *ngIf, * indicate that it is structural directive
Attribute directive don't add or remove  the elements from DOM. They only change the element they were placed on.Example is ngStyle

Angular 2

General Questions:
 What did you learn about Angular yesterday/this week?
 What are some of the reasons you would choose to use Angular in
your project?
 What did you like about working with Angular?
 How do you keep your Angular code more readable and maintainable?

 Animations Questions:
 How do you define transition between two states in Angular?
 How do you define a wildcard state?

 Architecture Questions:
 What is a good use case for ngrx/store?
 Can you talk about a bug related to a race condition, how to solve it
and how to test it?

 API Questions:
 What does this code do:
 @HostBinding('class.valid') isValid;
 <div *ngIf='someObservableData | async as data; else
loading'>{{data}}</div>
 <ng-template #loading>
 Loading Data...
 </ng-template>
 Why would you use renderer methods instead of using native element
methods?
 What is the point of calling renderer.invokeElementMethod(rendererEl,
methodName)?
 How would you control size of an element on resize of the window in a
component?
 What would be a good use for NgZone service?
 How would you protect a component being activated through the
router?
 How would you insert an embedded view from a prepared
TemplateRef?

 Template Syntax Questions:
 How can you add an active class to a selected element in a list
component?
 What is a template variable. How would you use it?

 Component Questions:
 What is the minimum definition of a component?
 What is the difference between a component and a directive?
 How do components communicate with each other?
 How do you create two way data binding in Angular?
 How would you create a component to display error messages
throughout your application?
 What does a lean component mean to you?

 Component Interaction & State Management Questions:
 How would you pass data from a parent component to a child
component?
 How would you pass data from a child component to a parent
component?
 Which components will be notified when an event is emitted?
 Tell me about the different ways how you would get data to your
components from a service and talk about why would you use one way
vs the other?
 How would you use cached data?

 Forms Questions:
 When do you use template driven vs model driven forms? Why?
 How do you submit a form?
 What's the difference between NgForm, FormGroup, and FormControl?
How do they work together?
 What's the advantage of using FormBuilder?
 How do you add form validation to a form built with FormBuilder?
 What's the difference between dirty, touched, and pristine on a form
element?
 How can you access validation errors in the template to display error
messages?
 What is async validation and how is it done?

 NgModules Questions:
 What is the purpose of NgModule?
 How do you decide to create a new NgModule?
 What are the attributes that you can define in an NgModule
annotation?
 What is the difference between a module's forRoot() and forChild()
methods and why do you need it?
 What would you have in a shared module?
 What would you not put shared module?
 What module would you put a singleton service whose instance will be
shared throughout the application (e.g. ExceptionService
andLoggerService)?
 What is the purpose of exports in a NgModule?
 Why is it bad if SharedModule provides a service to a lazy loaded
module?

 Services Questions:
 What is the use case of services?
 How are the services injected to your application?
 How do you unit test a service with a dependency?
 Why is it a bad idea to create a new service in a component like the
one below?
 let service = new DataService();

 Structural Directives Questions:
 What is a structural directive?
 How do you identify a structural directive in html?
 When creating your own structural directives, how would you decide on
hiding or removing an element? What would be the advantages or
disadvantages of choosing one method rather than the other?

 Style Guide Questions:
 What are some of the Angular Style Guide suggestions you follow on
your code? Why?
 Is it important to have a style guide? Why/not?

 Styling Questions:
 How would you select a custom component to style it.
 What pseudo-class selector targets styles in the element that hosts the
component?
 How would you select all the child components' elements?
 How would you select a css class in any ancestor of the component
host element, all the way up to the document root?
 What selector force a style down through the child component tree into
all the child component views?
 What does :host-context() pseudo-class selector targets?
 What does the following css do?
 :host-context(.theme-light) h2 {
 background-color: red;
 }

 Testing Questions:
 How do you mock a service to inject in a unit test?
 How do you mock a module in a unit test?

 Performance Questions:
 What tools would you use to find a performance issue in your code?
 What tools have you used to improve the performance of your
application?
 What are some ways you may improve your website's scrolling
performance?
 Explain the difference between layout, painting and compositing.
 Have you seen Jeff Cross's NgCruise talk on performance?

 Lifecycle Hooks Questions:
 What is the possible order of lifecycle hooks.
 When will ngOnInit be called?
 How would you make use of ngOnInit()?
 What would you consider a thing you should be careful doing on
ngOnInit()?
 What is the difference between ngOnInit() and constructor() of a
component?

 Pipes Questions:
 What is a pure pipe?
 What is an async pipe?
 What kind of data can be used with async pipe?
 How do you create a custom pipe?

 Routing Questions:
 What is the difference between RouterModule.forRoot() vs
RouterModule.forChild()? Why is it important?
 How does loadChildren property work?
 Do you need a Routing Module? Why/not?
 When does a lazy loaded module is loaded?
 Below link doesn't work. Why? How do I fix it?
 <div routerLink='product.id'></div>
 Can you explain the difference between ActivatedRoute and
RouterState?

 Observables/RxJS Questions:
 What is the difference between an observable and a promise?
 What is the difference between an observable and a subject?
 What are some of the angular apis that are using observables?
 How would you cache an observable data?
 How would you implement a multiple api calls that needs to happen in
order using rxjs?
 How would you make sure an api call that needs to be called only once
but with multiple conditions. Example: if you need to get some data in
multiple routes but, once you get it, you can reuse it in the routes that
needs it, therefor no need to make another call to your backend apis.
 How would you implement a brush behavior using rxjs?
 How would you implement a color picker with rxjs?
 If you need to respond to two different Observable/Subject with one
callback function, how would you do it?(ex: if you need to change the
url through route parameters and with prev/next buttons).

 TypeScript Questions:
 Why do you need type definitions?

 How would you define a custom type?
 What is the difference between an Interface and a Class?
 First line below gives compile error, second line doesn't. Why?
 someService.someMethod(x);
 someService['someMethod'](x);
 What are Discriminated union types?
 How do you define Object of Objects type in typescript?

 Security Questions:
 ...

 JavaScript Questions:
 Explain the difference between var, let and const key words.
 Could you make sure a const value is garbage collected?
 Explain Object.assign and possible use cases.
 Explain Object.freeze and possible use cases.
 Explain the code below. How many times the createVal function is
called?
 function createVal(){
 return Math.random();
 };

 function fun( val = createVal()){
 // Do something with val...
 }

 fun();
 fun(5);

 Coding Questions:
 What would these components render?
 import { Component, ContentChildren, Directive, Input,
QueryList } from '@angular/core';
 @Directive({selector: 'pane'})
 export class Pane {
 @Input() id: string;
 }

 @Component({
 selector: 'tab',
 template: `
 <div>panes: {{serializedPanes}}</div>
 `
 })
 export class Tab {
 @ContentChildren(Pane) panes: QueryList<Pane>;
 get serializedPanes(): string { return this.panes ?
this.panes.map(p => p.id).join(', ') : ''; }
 }

 @Component({
 selector: 'example-app',
 template: `
 <tab>
 <pane id="1"></pane>
 <pane id="2"></pane>
 <pane id="3" *ngIf="shouldShow"></pane>
 </tab>
 <button (click)="show()">Show 3</button>
 `,
 })
 export class ContentChildrenComp {
 shouldShow = false;
 show() { this.shouldShow = true; }
 }

 how to declare a component
 what type of directives are there
 how does rxjs differ from promises
 What is ChangeDetection.OnPush and what other
ChangeDetection strategies exist
 What is NgZone and what is it used for
 How do you declare an event binding
 How to declare a property binding
 What is ngModel and why is it considered a shorthand?
 Explain @Input @Output
 Explain NgModule and how a root module differs from a
feature module

 Explain where you would put shared components and where
you would put shared services
 Explain how you can use lay loading and what the benefit is
and also what impact this has on where you place
components and services
 What is AOT
 What is tree shaking
 What is “@Inject” and why is it needed
 What directive would you use to loop data?
 How would you import only the operators you need in Rxjs
and how would you import the whole lib and it what cases
would you use each strategy?
 • What is ngModule
 Difference between component and directives
 Why to use Module and diff between module and
component
 Default pipes
 Built in directives and their syntax's
 What is lazzy loading.
 Routing configuration
 Work flow of basic project structure
 “In Angular 2 how do you determine the active route”
 “Angular 2 data attributes”
 “Can't bind to 'formGroup' since it isn't a known property of
'form”
 “How do I create a singleton service in Angular 2?”
 “Angular2 exception: Can't bind to 'ngForIn' since it isn't a
known native property”
 “NativeScript/Angular - How to import global styles?”
 “Angular2 - What is the meanings of module.id in
component?”
 “Angular 2: How to use/import the http module?”
 “Angular2 material dialog has issues - Did you add it to

@NgModule.entryComponents?”
 “The pipe ' ' could not be found angular2 custom pipe”
 • “How do I call an Angular 2 pipe with multiple
arguments?”
 “Huge number of files generated for every Angular project”
 “Angular - Promise vs Observable”
 “Huge number of files generated for every Angular project”
 “Difference between Constructor and ngOnInit”
 “Angular 2 html binding”
 “Angular 2 HTTP GET with TypeScript error http.get(…).map
is not a function in [null]”
 “How to bundle an Angular 2, 4 & … app for production”
 “@Directive v/s @Component in angular2”
 “Angular 2 pipes details”
 “Angular 2 Forms Update”
 “Angular 2 Routing (3.0.0+) ”
 “Angular 2 RXJS Subjects and Observables with API
requests”
 “Angular Routing”
 “Directives”
 “How to Use ngif”

C# 7.0 & 7.1 , 7.2

1. Discards (C# 7.0)

a. Use with Out Param

private void DiiscardTest()
        {
            //Before  C# 7.0

            string s = "4";
            if (int.TryParse(s,out int x))
            {
                Console.WriteLine("This is an intger");
            }
            int y;            
            if (int.TryParse(s, out y))
            {
                Console.WriteLine("This is an integer");
            }

            //After C# 7.0
            if (int.TryParse(s, out int _))
            {
                Console.WriteLine("This is an intger");
            }

            if (int.TryParse(s, out _))
            {
                Console.WriteLine("This is an intger");
            }
//It is applicable on multiparameter

        }

b. Discard With Tuple

private void DiscardWithTuple()
        {
            Program p = new Program();

            //Before C# 7.0
            (int id, String name) = p.GetDetail();

            //After C$ 7.0
            (int ID, _) = p.GetDetail();

        }

        private (int id, String name) GetDetail() => (1, "red");

c. Use Discard alone

 private void DiscardAlone()
        {
            //Before C# 7.0
            int x = 90;
            bool y = x > 90 ? UpdateID() : UpdateName();

            //After C# 7.0
            _ = x > 90 ? UpdateID() : UpdateName();
        }

        private bool UpdateID()
        {
            //Updated...
            //............
            return true;
        }

        private bool UpdateName()
        {
            //Updated...
            //............
            return true;
        }

d. Use Discard in Pattern Matching

private void DoWork(dynamic c)
        {
            if (c is int)
            {
                Console.WriteLine("c is an intger");
            }
            else if (c is string)
            {
                Console.WriteLine("c is a String");
            }
            else if(c is var _)
            {
                Console.WriteLine("Unknow Type");
            }
        }

e. Discard with Tasks

Before C# 7.0

static void Main(string[] args) => PrintOddNumbers(20);  
  
private static void PrintOddNumbers(int maxNumber)  
{  
  Task task = Run(() => {   
    for (int i = 1; i < maxNumber; i += 2)  
    {  
        Write($"{i}\t");  
        Sleep(500);  
    }  
    });              
   Delay(300*maxNumber).Wait();  

In above example there is no use of task, so using discard we can avoid task

After C# 7.0

private static void PrintOddNumbers(int maxNumber)  
{  
  _= Run(() => {   
    for (int i = 1; i < maxNumber; i += 2)  
    {  
        Write($"{i}\t");  
        Sleep(500);  
    }  
    });              
   Delay(300*maxNumber).Wait();  

2. 'is' type Pattern Matching


Before C# 7.0 
        private static void PrintObject(dynamic x)
        {
            if (x is Seller)
            {
                var c = x as Seller;
                WriteLine($"Seller Id : {c.Id} Seller Name {c.Name}");
            }
            if (x is Manager)
            {
                var p = x as Manager;
                WriteLine($"Manager Id : {p.ManagertId} Manager Name {p.Name}");
            }
            else
                WriteLine("Unknown type");
        }

After C# 7.0 

private static void PrintObject(dynamic x)
        {
            if (x is Seller s)
            {
                WriteLine($"Seller Id : {s.Id} Seller Name {s.Name}");
            }
            if (x is Manager m)
            {
                WriteLine($"Manager Id : {m.ManagertId} Manager Name {m.Name}");
            }
            else
                WriteLine("Unknown type");
        }

3. Pattern matching with switch

private static void PrintObject(dynamic x)  
        {  
            switch (x)  
            {  
                case Customer c:  
                    WriteLine($"Customer Id : {c.Id} Customer Name {c.Name}");  
                    break;  
                case Product p:  
                    WriteLine($"Product Id : {p.ProductId} Product Name {p.Name}");  
                    break;  
                default:  
                    WriteLine("Unknown type");  
                    break;  
            }              
        } 


4. switch statement with when condition

private void PrintShapeType(object shape)  
        {  
            switch (shape)  
            {  
                case Triangle t when t.SideA == t.SideB && t.SideB == t.SideC:  
                    WriteLine($"Equilateral Triangle");  
                    break;  
  
                case Triangle t:  
                    WriteLine($"Not a Equilateral Triangle");  
                    break;  
  
                case Rectangle r when r.Height == r.Width:  
                    WriteLine($"Square");  
                    break;  
  
                case Rectangle r:  
                    WriteLine($"Rectangle");  
                    break;  
  
                default:  
                    WriteLine($"Unknow shape");  
                    break;  
            }  
        }  


5. Does Sequence matter for switch


Yes sequence matter first matching case will excute first.


using static System.Console;  
namespace CaseExpressionSequence  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            PrintData(0);  
            PrintData(2);  
            PrintData(5);  
            PrintData(false);  
            PrintData(true);  
            PrintData(55.5);  
        }  
  
        private static void PrintData(object obj)  
        {  
            switch (obj)  
            {  
                case 0:  
                case 5:  
                case true:  
                    WriteLine($"you passed {obj}");  
                    break;  
                case int number:  
                    WriteLine($"you passed a numeric value");  
                    break;  
                case bool b:  
                    WriteLine($"you passed a boolean value");  
                    break;  
                default:  
                    WriteLine($"Invalid data");  
                    break;  
            }  
        }  
    }  
}  


6. Async method returning Task


class Program1
        {
            static void Main(string[] args)
            {                
                PrintPrimeNumbers(100);
                ReadKey();
            }

            private static async Task PrintPrimeNumbers(int maxNumber)
            {
                await Run(() =>
                {
                    WriteLine($"printing prime numbers between 0 and {maxNumber}");
                    List primes = new List();
                    bool isPrime;

                    for (int number = 2; number <= maxNumber; number++)
                    {
                        isPrime = true;
                        foreach (var prime in primes.Where(x => x <= Sqrt(number)))
                        {
                            if (number % prime == 0)
                            {
                                isPrime = false;
                                break;
                            }
                        }
                        if (isPrime)
                        {
                            WriteLine(number);
                            primes.Add(number);
                        }
                    }
                });
            }
        }

7. Same way you can reurn Task

8. Acynch method can return void

9. Async method returning ValueTask

In above example we cna return ValueTask instead of Task because task is frreqence type and we need

10. To use ValueTask, you must need to install NuGet package “System.Threading.Tasks.Extensions”.

11. Async Main (Main Method returning Task)

Main function can return now Task, Task, it may be async also.

12. Can we have more than one Main method in a Project?

Yes  , it is possible in C# 7.0, Main method where you want to start executaion set it in property window startup project

13. Infer Tuple Element Names

// Tuple created without Tuple keyword
class Program  
    {  
        static void Main(string[] args)  
        {  
            var activity = ActivityTracker.GetActivity();  
            WriteLine($"Activity Data: \n Steps: {activity.Item1}\n Distance: {activity.Item2} Km.\n Calories Burned: 

{activity.Item2}\n Sleep Time: {activity.Item4}\n Heart Rate: {activity.Item5}\n Weight: {activity.Item6}");  
        }  
    }  
  
    public class ActivityTracker  
    {  
        public static (int, double, double, TimeSpan, double, double) GetActivity()  
        {  
            int steps = 7000;  
            double distance = 5.2;  
            double caloriesBurned = 30.02;  
            TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
            double heartRate = 72;  
            double weight = 75.5;  
            var activity = (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
            return activity;  
        }  
    }  

13. Assign a name to every member of tuple

class Program  
    {  
        static void Main(string[] args)  
        {  
            var activity = GetActivity();  
            WriteLine($"Activity Data: \n Steps: {activity.steps}\n Distance: {activity.distance} Km.\n Calories Burned: 

{activity.caloriesBurned}\n Sleep Time: {activity.sleepTime}\n Heart Rate: {activity.heartRate}\n Weight: 

{activity.weight}");  
        }  
    }  
  
    public class ActivityTracker  
    {  
        public static (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double 

weight) GetActivity() => (steps: 7000, distance: 5.2, caloriesBurned: 30.02, sleepTime: new TimeSpan(6, 20, 00), heartRate: 

72, weight: 75.5);  
    }  


14. Deconstructing Tuple


class Program  
    {  
        static void Main(string[] args)  
        {  
            (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double weight) = 

GetActivity();  
            WriteLine($"Activity Data: \n Steps: {steps}\n Distance: {distance} Km.\n Calories Burned: {caloriesBurned}\n 

Sleep Time: {sleepTime}\n Heart Rate: {heartRate}\n Weight: {weight}");  
        }  
  
        public static (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double 

weight) GetActivity() => (steps: 7000, distance: 5.2, caloriesBurned: 30.02, sleepTime: new TimeSpan(6, 20, 00), heartRate: 

72, weight: 75.5);  
    }  

15 Inferring element name of a Tuple


public static void GetActivity()  
 {  
     int steps = 7000;  
     double distance = 5.2;  
     double caloriesBurned = 30.02;  
     TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
     double heartRate = 72;  
     double weight = 75.5;  
     var activity = (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
  
     WriteLine($"Activity Data: \n Steps: {activity.steps}\n Distance: {activity.distance} Km.");  
 }  



16. Default keyword before C# 7.0

Before C# 7.1
int a = default(int);  
        bool b = default(bool);  
        string c = default(string);  
        int? d = defailt(int?);  

After C# 7.1
int a = default;  
bool b = default;  
string c = default;  
int? d = default;  
Action action = default;  
Predicate predicate = default;  
List list = default;  
Dictionary dictionary = default;  
public int Add(int x, int y = default, int z = default)  
 {  
     return x + y + z;  
 } 



17.Pattern Matching with Generics 


public void PrintProduct(T product) where T:Product  
{  
    switch (product)  
    {  
        case ConvenienceProduct p:  
            WriteLine("Convenience Product");  
            // ---- print other information  
            break;  
        case ShoppingProduct p:  
            WriteLine("Shopping Product");  
            // ---- print other information  
            break;  
  
        case SpecialtyProduct p:  
            WriteLine("Specialty Product");  
            // ---- print other information  
            break;  
        default:  
            WriteLine("General Product");  
            break;  
    }  

public void Print(T type) where T : class  
{  
    switch (type)  
    {  
        case Customer customer:  
            WriteLine($"{customer.Id} {customer.Name} {customer.CustomerType} {customer.MonthlyPurchase}");  
            break;  
        case Product product:  
            WriteLine($"{product.ProductId} {product.ProductName} {product.ProductDescription}");  
            break;  
        default:  
            break;  
    }  


18. in Visual studio 2017 support for inline variable declaration has been added and it also provides intellisence for inline variable declaration with information id “IDE0018”.


19. In C# 7 we can use ‘ref’ for return a variable from a method i.e. a method can return variable with reference.


20. Use ref kyword as a local and return variable

class Program  
    {  
        public ref int GetFirstOddNumber(int[] numbers)  
        {  
            for (int i = 0; i < numbers.Length; i++)  
            {  
                if (numbers[i] % 2 == 1)  
                {  
                    return ref numbers[i]; //returning as reference  
                }  
            }  
            throw new Exception("odd number not found");  
        }  
        static void Main(string[] args)  
        {  
            Program p = new Program();  
            int[] x = { 2, 4, 62, 54, 33, 55, 66, 71, 92 };  
            ref int oddNum = ref p.GetFirstOddNumber(x); //storing as reference  
            WriteLine($"\t\t\t\t{oddNum}");  
            oddNum = 35;  
            for (int i = 0; i < x.Length; i++)  
            {  
                Write($"{x[i]}\t");                  
            }  
            ReadKey();  
        }  
    }  

Output 2 4 62 35 55 66 71 92

So if will update oddNum variable than it will updated in array as well

21. Use ref as a return type

class Program  
    {  
        static void Main(string[] args)  
        {  
            GetEmployee() = new Employee { Id = 2, Name = "Banketeshvar", Age = 28 };  
        }  
    }  
  
    class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public int Age { get; set; }  
    }  
  
    class DummyEmployees  
    {  
        public static Employee employee = null;  
        public static ref Employee GetEmployee()  
        {  
            if (employee == null)  
            {  
                employee = new Employee { Id = 1, Name = "Manish Sharma", Age = 27 };  
            }  
            return ref employee;  
        }  
    }  
}   

22. Local functions or nested functions

using static System.Console;  
namespace UseLocalFunctions {  
    class Program {  
        static void Main(string[] args) {  
            void Add(int x, int y) {  
                WriteLine($ "Sum of {x} and {y} is : {x + y}");  
            }  
            void Multiply(int x, int y) {  
                WriteLine($ "Multiply of {x} and {y} is : {x * y}");  
                Add(30, 10);  
            }  
            Add(20, 50);  
            Multiply(20, 50);  
        }  
    }  
}  

It can also return value.
Factoril wihtout recursive function

private static long GetFactorialUsingLocal(int number) {  
    if (number < 0) throw new ArgumentException("negative number", nameof(number));  
    if (number == 0) return 1;  
    long result = number;  
    while (number > 1) {  
        Multiply(number - 1);  
        number--;  
    }  
    void Multiply(int x) => result *= x;  
    return result;  
}  

23. Binary Literals


You can use “0B” or “0b” for binary literal. So, in C# 7, you can represent integer in 3 ways - decimal literal, hexadecimal literal, and binary literal. Before C# 7 there were only two literal allowed decimal and hexa

 int a = 50; // decimal representation of 50  
            int b = 0X32; // hexadecimal representation of 50  
            int c = 0B110010; //binary representation of 50  
            //Represent 100 in decimal, hexadecimal & binary  
            int d = 50 * 2; // decimal represenation of 100   
            int e = 0x32 * 2; // hexadecimal represenation of 100  
            int f = 0b110010 * 2; //binary represenation of 100  

24. Digit Separators

We can use one or more than one Underscore( _ ) character for digit separators. Sometimes, it is required when we are going to represent a big number.

region Using Digit Separators  
            int binaryData = 0B0010 _0111_0001_0000; // binary value of 10000   
            int hexaDecimalData = 0X2B _67; //HexaDecimal Value of 11,111   
            int decimalData = 104 _567_789;  
            int myCustomData = 1 ___________2__________3___4____5_____6;  
            double realdata = 1 _000 .111 _1e1_00;  
            WriteLine($ " binaryData :{binaryData} \n hexaDecimalData: {hexaDecimalData} \n decimalData: {decimalData} \n myCustomData: {myCustomData} \n realdata: {realdata}");#  
            endregion  

25. Pattern matching


var myData = "Custom Data";  
            var myData2 = myData is string ? "String" : "Not a string";  
            var myData3 = myData is string a ? a : "Not a String";  
            WriteLine(myData2);  
            WriteLine(myData3);  
            //Example 2   
            var x = 10;  
            dynamic y = 0b1001;  
            var sum = y is int ? $ "{y * x}" : "Invalid data";  
            WriteLine(sum);  

26. Deconstruction

“deconstruction” is a concept which allows us to access a tuple member directly with its name without using any tuple variable name.


37. Throw Expressions


In C# 7, we can throw an exception directly through expression.
class Program {  
    static void Main(string[] args) {  
        var a = Divide(10, 0);  
    }  
    public static double Divide(int x, int y) {  
        return y != 0 ? x % y : throw new DivideByZeroException();  
    }  
} // This is just a sample script. Paste your real code (javascript or HTML) here.  
if ('this_is' == /an_example/) {  
    of_beautifier();  
} else {  
    var a = b ? (c % d) : e[f];  
}  

Followers

Link