CSharp Interview Questions And Answers

1. Reflection and Dynamic keyword in .NET

Ans. http://questpond.over-blog.com/article-questpond-s-interview-questions-and-answers-on-reflection-and-dynamic-keyword-in-net-124429332.html

 

http://www.besttechtools.com/DotnetArticles/article/difference-between-Object-Dynamic-and-Var
http://www.c-sharpcorner.com/uploadfile/ff2f08/object-vs-var-vs-dynamic-type-in-c-sharp/

http://www.dotnetfunda.com/interviews/show/6303/how-can-you-prevent-the-class-from-being-inherited-by-other-classes-wi
http://www.c-sharpcorner.com/UploadFile/4b0136/async-and-await-in-asynchronous-programming-in-C-Sharp/
https://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
https://appendto.com/2016/02/working-promises-angularjs-services/
https://www.airpair.com/angularjs
http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx
https://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/
http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
http://firstcrazydeveloper.com/Blogs/BlogView.html/46/importance-of-config-and-run-blocks-in-angularjs
https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
http://www.c-sharpcorner.com/uploadfile/dev4634/understanding-http-interceptors-in-angular-js/
http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
http://www.tothenew.com/blog/angularjs-copy-vs-extend/
http://www.tothenew.com/blog/angularjs-copy-vs-extend/
http://www.talkingdotnet.com/grunt-js-interview-questions/
https://scotch.io/tutorials/angular-routing-using-ui-router
https://www.codeproject.com/Articles/841776/AngularJS-ui-router
http://www.w3schools.com/js/js_array_methods.asp
https://www.ng-book.com/p/Caching/
https://www.phase2technology.com/blog/caching-json-arrays-using-cachefactory-in-angularjs-1-2-x/
http://blog.rgarom.com/cookiestore-vs-localstorage-vs-sessionstorage/
http://www.aspsnippets.com/Articles/AngularJS-LocalStorage-and-SessionStorage-example.aspx
http://www.c-sharpcorner.com/uploadfile/8911c4/different-between-method-overriding-method-hiding-new-keyw/
http://odetocode.com/blogs/scott/archive/2014/05/28/compile-pre-and-post-linking-in-angularjs.aspx
https://github.com/angular/angular.js/wiki/Understanding-Scopes

http://einterviewquestionsandanswers.com/interview-questions-and-answers/
https://www.ng-book.com/p/Angular-Module-Loading/
http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/
https://logcorner.com/angular-js-token-based-authentication-using-asp-net-identity-and-asp-net-web-api/

https://www.servage.net/blog/2013/04/08/rest-principles-explained/
https://www.codeproject.com/Articles/816448/Virtual-vs-Override-vs-New-Keyword-in-Csharp

http://www.programmerinterview.com/index.php/database-sql/clustered-vs-non-clustered-index/
http://blog.globalknowledge.com/2012/02/23/disadvantages-of-indexing-in-sql-server/
http://www.c-sharpcorner.com/blogs/what-is-magic-table-in-sql-server1

http://blog.xebia.com/differences-between-providers-in-angularjs/
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting
https://www.undefinednull.com/2014/06/26/explaining-call-and-apply-in-javascript-through-mr-dot-dave/
http://www.jquerybyexample.net/2012/05/empty-vs-remove-vs-detach-jquery.html

https://toddmotto.com/factory-versus-service
http://fdietz.github.io/recipes-with-angular-js//using-forms/displaying-form-validation-errors.html
http://www.bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q/

.Net Framework

TFS

OOPs

Tortoise SVN

C#

Git

Design Pattern & Practices

JIRA

Asp.Net

Visual Studio

Asp.Net MVC

.Net Reflector

Angular JS

NUnit

JavaScript

Advanced Rest Client

ADO.NET

Sublime Text

SQL

Fiddler

Azure

.Net Assembly Information

Node.JS

Firebug

Asp.Net Web API

WCF Test Client

WCF

Style Cop

Rest WCF

Ghost Doc

JQuery

 

JSON

 

XML

 

SOAP

 

Typescript

 

Entity Framework

 

LINQ

 

Web Services

 

AJAX

 

HTML & HTML5

 

CSS & CSS3

 

Bootstrap

BrowserStack

Dapper                 

Agile Methodology

Service Stack

Beyond Compare

Mongo DB

 

Hadoop

 

MEAN

 

 

https://blog.cdemi.io/exploring-visual-studio-15-preview-and-playing-with-c-7/

 

Tuples

The most common reason to use Tuples is to have multi results. C# 7 supports multiple value returns.  the compiler will use the new ValueTuple struct. 

public (int x, int y) Compute(){

    return (1, 2);

}

 

Tuples were available before C# 7 as an API, but had many limitations. Most importantly, the members of these tuples were named Item1Item2and so on. The language support enables semantic names  for the fields of a Tuple.

 

Tuple Deconstruction

You can also separate a tuple into its parts.

Calling GetTallies and assigning the return value to two separate variables:

(int tallyOne, int tallyTwo) = GetTallies();

var also works:

(var s, var c) = GetTallies();

You can also use shorter syntax, with var outside of ():

var (s, c) = GetTallies();

You can also deconstruct into existing variables

(s, c) = GetTallies();

 

Differences between ValueTuple and Tuple

The primary reason for introduction of ValueTuple is performance.

Type name

ValueTuple

Tuple

Class or structure

struct

class

Mutability (changing values after creation)

mutable

immutable

Naming members and other language support

yes

no (TBD)

 

Out variables

C# 7.0 has direct support to use them in at the time when we are passing an argument. 

The existing syntax that supports out parameters has been improved in this version.

Up to C# 6.0, using out parameters isn’t as fluid as we’d like. Up to C# 6.0, if we want to call a method with ‘out’ parameters we first have to declare variables to pass to it. Since we aren’t initializing these variables (they are going to be overwritten by the method after all), we also cannot use var to declare them, but need to specify the full type

Previously, you would need to separate the declaration of the out variable and its initialization into two different statements:

int numericResult;
if (int.TryParse(input, out numericResult))
    WriteLine(numericResult);
else
    WriteLine("Could not parse input");

You can now declare out variables in the argument list of a method call, rather than writing a separate declaration statement:

if (int.TryParse(input, out int result))

    WriteLine(result);

else

    WriteLine("Could not parse input");


 

public void PrintHeight()

{

    CalculateHeight(out int height);

    WriteLine($"({height})");

}

 

·         The code is easier to read.

o    You declare the out variable where you use it, not on another line above.

·         No need to assign an initial value.

o    By declaring the out variable where it is used in a method call, you can't accidentally use it before it is assigned.

The most common use for this feature will be the Try pattern. In this pattern, a method returns a bool indicating success or failure and an out variable that provides the result if the method succeeds.

 

Ref Return and Ref Local

Previously, Ref keyword is used to pass parameters as reference. Once the parameter value is changes in the method, calling method will be reflected too. We must declare and initialize the variable before passing it with ref keyword. 

In C# 7, Just like you can pass parameters by reference, you can now return them by reference, and also store them by reference in local variables. 

 

Local functions

Local functions are not available outside of it and have access all local variables, async/await and lambda syntax.

public void Foo(int x)
{
    return Localfunction();
    
    int Localfunction()
    {
        return x;
    }
}

 

Throw expressions

C# 7.0 allows throw an exception in middle of the expression. 

class Person
{
    public string Name { get; }
    public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
    public string GetFirstName()
    {
        var parts = Name.Split(" ");
        return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
    }
    public string GetLastName() => throw new NotImplementedException();
}

 

 

Pattern Matching

C# 7 supports pattern matching for is and switch expression to extend the existing pattern matching capabilities. 

Is Expression

The is operator is used to extend the pattern matching capabilities. Is operator can be used to declare new variables and assign values.
 

void Find( object obj)
{
     //following null is constant pattern
     if (obj is null)  return;
    
     //datatype pattern, string is datatype that can be check directly     
     if (obj  is  string st)
       //code goes here
     else
       return; 
}

 

Switch Expression

Switch statement is already a part of C#, in C# 7 switch statement has been extended with pattern matching. The Switch statement is slightly different than is expression, when you declare the type and variable at the beginning of the case expression.
 

public static int DiceSum4(IEnumerable<object> values)
{
    var sum = 0;
    foreach (var item in values)
    {
        switch (item)
        {
            case 0:
                break;
            case int val:
                sum += val;
                break;
            case IEnumerable<object> subList when subList.Any():
                sum += DiceSum4(subList);
                break;
            case IEnumerable<object> subList:
                break;
            case null:
                break;
            default:
                throw new InvalidOperationException("unknown item type");
        }
    }
    return sum;
}

 

Digit separators

C# 7 consider _ (underscore) as a digit separator. More than one digit separator allows at any place to improve readability. 
 

var d = 123_456;

var x = 0xAB_CD_EF;

 

The separators have no semantic impact - they are simply ignored.

 

Binary literals

C# 7 introduces binary literals to use bit patterns directly instead of having to know hexadecimal notation. 
 

var b = 0b1010_1011_1100_1101_1110_1111;

This can be useful for working with binary flags. 

 

Extended expression bodied members list

Expression-bodied members feature is introduced in C# 6, are now allowed on accessors, constructors and finalizers. 

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script>
               function LaunchHelp() {
            try {

                var surl = "http://www.google.com";
                if (validateURL(surl))
                    window.open(surl, '_blank', 'toolbar=no,menubar=no,status=yes');
                else {
                    throw new InvalidURLException();
                }
            } catch (e) {
                if (e instanceof InvalidURLException)
                    alert(e.message);
            }
        }

        function InvalidURLException() {
            this.message = "An attempt was made to open a webpage of foreign domain. No allowed.";
            this.toString = function () {
                return this.message
            };
        }

        function validateURL(surl) {
            var url = parseURL(surl);
            var urlHostname = url.hostname.trim();

            if (urlHostname == '') {
                return true;
            }
            else {
                if (urlHostname.toUpperCase() == location.hostname.trim().toUpperCase()) {
                    return true;
                }
                else
                    return false;
            }
        }

        function parseURL(url) {
            var a = document.createElement('a');
            a.href = url;
            return {
                source: url,
                protocol: a.protocol.replace(':', ''),
                hostname: a.hostname,
                host: a.host,
                port: a.port,
                query: a.search,
                params: (function () {
                    var ret = {},
                        seg = a.search.replace(/^\?/, '').split('&'),
                        len = seg.length, i = 0, s;
                    for (; i < len; i++) {
                        if (!seg[i]) { continue; }
                        s = seg[i].split('=');
                        ret[s[0]] = s[1];
                    }
                    return ret;
                })(),
                file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
                hash: a.hash.replace('#', ''),
                path: a.pathname.replace(/^([^\/])/, '/$1'),
                relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
                segments: a.pathname.replace(/^\//, '').split('/')
            };
        }



    </script>
</head>
<body>
    <h1>This is Test 1 Page.</h1>
    <button id="btnRedirect" name="btnRedirect" onclick="LaunchHelp()">Redirect</button>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Helper
{
    public class RequestExtensions
    {
        System.Web.HttpRequest request = HttpContext.Current.Request;
        public bool IsLocalUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return false;
            }

            Uri absoluteUri;
            if (Uri.TryCreate(url, UriKind.Absolute, out absoluteUri))
            {
                return String.Equals(request.Url.Host, absoluteUri.Host,
                            StringComparison.OrdinalIgnoreCase);
            }
            else
            {
                bool isLocal = !url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
                    && !url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)
                    && Uri.IsWellFormedUriString(url, UriKind.Relative);
                return isLocal;
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Helper;

namespace RedirectionalAttackExample
{
    public partial class Hello : System.Web.UI.Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Helper.RequestExtensions requestExtension = new RequestExtensions();
            string returnUrl = Request.QueryString["redirectPage"];
            if (requestExtension.IsLocalUrl(returnUrl))
            {
                Response.Redirect(returnUrl);
            }
            else
            {
                Response.Redirect("default.aspx");
            }
            
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace RedirectionalAttackExample
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnRedirect_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("Hello.aspx?redirectPage={0}", Convert.ToString(txtRedirectUrl.Text)));
        }
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EnumExample
{
    public enum Days
    {
        Sunday = 1,
        Monday = 2,
        Tuesday = 3
    }


    public enum Laptops
    {
        [StringValue("Dell")]
        DELL,
        [StringValue("Hp")]
        HP,
        [StringValue("Samsung")]
        SAMSUNG,
        [StringValue("Sony")]
        SONY,
        [StringValue("Apple")]
        APPLE        
    }


    public class StringValueAttribute : System.Attribute
    {
        private string _value = string.Empty;
        public StringValueAttribute(string value)
        {
            _value = value;
        }
        public string Value
        {
            get { return _value; }
        }
    }
    class Program
    {
        private static Hashtable _enumValuesCache = new Hashtable();      

        public static string GetEnumStringValue(Enum key)
        {
            string enumValue = string.Empty;
            Type type = key.GetType();

            if (_enumValuesCache.ContainsKey(key))
                enumValue = (_enumValuesCache[key] as StringValueAttribute).Value;
            else
            {
                FieldInfo objFieldInfo = type.GetField(key.ToString());
                StringValueAttribute[] _stringValueAttribute = objFieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (_stringValueAttribute.Length > 0)
                {
                    _enumValuesCache.Add(key, _stringValueAttribute[0]);
                    enumValue = _stringValueAttribute[0].Value;
                }
            }

            return enumValue;
        }
        static void Main(string[] args)
        {
            Console.WriteLine(Days.Tuesday);
            Console.WriteLine((int)Days.Tuesday);
            Console.WriteLine(GetEnumStringValue(Laptops.SAMSUNG));
            Console.ReadLine();

        }
    }
}
{
  "id": 123,
  "name": "Pankaj Kumar",
  "address": {
    "street": "El Camino Real",
    "city": "San Jose",
    "zipcode": 95014
  },
  "experiences": [
    {
      "companyid": 20,
      "companyname": "Genpact Headstrong"
    },
    {
      "companyid": 77,
      "companyname": "Mind Tree LTD"
    },
    {
      "companyid": 89,
      "companyname": "TCS"
    },
    {
      "companyid": 22,
      "companyname": "Hello World LTD"
    }
  ],
  "phoneNumber": 9988664422,
  "role": "Developer"
}
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonAddAndUpdate
{
    class Program
    {
        private string jsonFile = @"C:\Users\mk9\Documents\visual studio 2015\Projects\JsonAddAndUpdate\JsonAddAndUpdate\user.json";
        private void AddCompany()
        {
            Console.WriteLine("Enter Company ID : ");
            var companyId = Console.ReadLine();
            Console.WriteLine("\nEnter Company Name : ");
            var companyName = Console.ReadLine();

            var newCompanyMember = "{ 'companyid': " + companyId + ", 'companyname': '" + companyName + "'}";
            try
            {
                var json = File.ReadAllText(jsonFile);
                var jsonObj = JObject.Parse(json);
                var experienceArrary = jsonObj.GetValue("experiences") as JArray;
                var newCompany = JObject.Parse(newCompanyMember);
                experienceArrary.Add(newCompany);

                jsonObj["experiences"] = experienceArrary;
                string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(jsonFile, newJsonResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Add Error : " + ex.Message.ToString());
            }
        }

        private void UpdateCompany()
        {
            string json = File.ReadAllText(jsonFile);

            try
            {
                var jObject = JObject.Parse(json);
                JArray experiencesArrary = (JArray)jObject["experiences"];
                Console.Write("Enter Company ID to Update Company : ");
                var companyId = Convert.ToInt32(Console.ReadLine());

                if (companyId > 0)
                {
                    Console.Write("Enter new company name : ");
                    var companyName = Convert.ToString(Console.ReadLine());

                    foreach (var company in experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId))
                    {
                        company["companyname"] = !string.IsNullOrEmpty(companyName) ? companyName : "";
                    }

                    jObject["experiences"] = experiencesArrary;
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(jsonFile, output);
                }
                else
                {
                    Console.Write("Invalid Company ID, Try Again!");
                    UpdateCompany();
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine("Update Error : " + ex.Message.ToString());
            }

        }

        private void DeleteCompany()
        {
            var json = File.ReadAllText(jsonFile);
            try
            {
                var jObject = JObject.Parse(json);
                JArray experiencesArrary = (JArray)jObject["experiences"];
                Console.Write("Enter Company ID to Delete Company : ");
                var companyId = Convert.ToInt32(Console.ReadLine());

                if (companyId > 0)
                {
                    var companyName = string.Empty;
                    var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);

                    experiencesArrary.Remove(companyToDeleted);
                   
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(jsonFile, output);
                }
                else
                {
                    Console.Write("Invalid Company ID, Try Again!");
                    UpdateCompany();
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        private void GetUserDetails()
        {
            var json = File.ReadAllText(jsonFile);
            try
            {
                var jObject = JObject.Parse(json);

                if(jObject!=null)
                {
                    Console.WriteLine("ID :" + jObject["id"].ToString());
                    Console.WriteLine("Name :" + jObject["name"].ToString());

                    var address = jObject["address"];
                    Console.WriteLine("Street :" + address["street"].ToString());
                    Console.WriteLine("City :" + address["city"].ToString());
                    Console.WriteLine("Zipcode :" + address["zipcode"]);
                    JArray experiencesArrary = (JArray)jObject["experiences"];
                    if (experiencesArrary != null)
                    {
                        foreach (var item in experiencesArrary)
                        {
                            Console.WriteLine("company Id :" + item["companyid"]);
                            Console.WriteLine("company Name :" + item["companyname"].ToString());
                        }

                    }
                    Console.WriteLine("Phone Number :" + jObject["phoneNumber"].ToString());
                    Console.WriteLine("Role :" + jObject["role"].ToString());

                }                
            }
            catch (Exception)
            {

                throw;
            }

        }
        static void Main(string[] args)
        {
            Program objProgram = new JsonAddAndUpdate.Program();
            
            Console.WriteLine("Choose Your Options : 1 - Add, 2 - Update, 3 - Delete, 4 - Select \n");
            var option = Console.ReadLine();
            switch (option)
            {
                case "1":
                    objProgram.AddCompany();
                    break;
                case "2":
                    objProgram.UpdateCompany();
                    break;
                case "3":
                    objProgram.DeleteCompany();
                    break;
                case "4":
                    objProgram.GetUserDetails();
                    break;
                default:
                    Main(null);
                    break;
            }
            Console.ReadLine();

        }
    }
}