.NET basics Flashcards

1
Q

Abstract class vs interface

A

An abstract class allows you to create functionality that subclasses can implement or override. 

An interface only allows you to define functionality, not implement it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

string vs. System.String

A

In C#, the string keyword is an alias for String; therefore, String and string are equivalent.
It’s recommended to use the provided alias string as it works even without using System;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Are Strings Immutable in c#

A

String objects are immutable: they can’t be changed after they’ve been created.
All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Advantages of Using Interface

A

Interface allow us to develop loosely couples systems , dependency injection and make unit testing and mocking easier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When do you use abstract class?

A

Generally for base controllers or base classes where we don’t want an object of it to be created. So we use abstract class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is entity framework?

A

Entity Framework is an open-source ORM framework for .NET applications supported by Microsoft.
It enables developers to work with data using objects of domain-specific classes without focusing on the underlying database tables and columns where this data is stored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the features of Entity Framework?

A

Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve data from the underlying database. The database provider will translate these LINQ queries to the database-specific query language (e.g. SQL for a relational database). EF also allows us to execute raw SQL queries directly to the database.

Caching: EF includes the first level of caching out of the box. So, repeated querying will return data from the cache instead of hitting the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is context class in Entity Framework?

A

The context class is a most important class while working with EF 6 or EF Core.
It represent a session with the underlying database using which you can perform CRUD (Create, Read, Update, Delete) operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does Entity Framework work?

A

Entity Framework API includes the ability to map domain (entity) classes to the database schema, translate and execute LINQ queries to SQL, track changes occurred to the entities during lifetime, and save changes to the database

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to create a Custom Context class in EF?

A

By inheriting DbContext class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to register a Custom Context class in EF?

A

Register the Custom Context class in the ConfigureServices of the startup.cs file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the role of ConfigureServices() ?

A

It takes care of registering the services consumed across the application using Dependency Injection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the role of Configure() ?

A

It is used to add Middleware components to the IApplicationBuilder instance available in the method itself.
Using this method we can build middleware such as routing , authentication and session as well as third party middleware

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what is wwwrootfolder in .NET core?

A

It contains static files such as HTML , CSS and JavaScript and only these files inside the wwwrootfolder can be served over HTTP requests

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is garbage collection?

A

A low priority process that serves as an automatic memory manager which manages the allocation and release of memory for applications

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is delegate?

A

A delegate in .NET is similar to a function pointer in C/C++.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Disadvantages of Query String

A

All the attributes and values are visible to the end user. Therefore, they are not secure. - There is a limit to URL length of 255 characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are PUT, POST and PATCH ?

A

POST is used for creating a resource ( does not matter if it was duplicated )

PUT is for checking if a resource exists then update, else create new resource(Body contains whole entity to be updated)

PATCH is always for updating a resource(Body may contain only required fields)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to make public APIs more secure ?

A

By using Authentication and Authorization well , we can secure the APIs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

ViewBag vs ViewData

A

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

ViewData requires typecasting for complex data type and check for null values to avoid error.

ViewBag doesn’t require typecasting for complex data type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How to configure custom routing in .NET mvc?

A

Inside Configure () method of Startup.cs , use app.UseMVC() method that takes two parameters.
For example ,
app.UseMvc(routes=>{routes.MapRoute(“default”,”{controller=Home}/{action=Index}/{id?}”)})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is Attribute routing ?

A

Attribute Routing enables us to define routing on top of the controller action method.
For example,
public class HomeController: Controller
{
//URL: /Mvctest
[Route(“Mvctest”)] //Mvctest corresponds to absolute URL
public ActionResult Index()
ViewBag.Message = “Welcome to ASP.NET MVC!”;
return View();
}}

We can also set a common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to do Authorization in .Net MVC?

A

Authorization can be done by using [authorize] attribute on top of controller action method or inside configureServices of startup.cs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

what does [AllowAnonymous] do?

A

This allows anonymous requests to be processed for those that don’t need any authorization . This works exact opposite of [Authorize] attribute

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Class vs struct

A

Classes Only:
Can support inheritance
Are reference (pointer) types
The reference can be null
Have memory overhead per new instance

Structs Only:
Cannot support inheritance
Are value types
Are passed by value (like integers)
Cannot have a null reference (unless Nullable is used)
Do not have a memory overhead per new instance - unless ‘boxed’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are common between class and struct ?

A

Are compound data types typically used to contain a few variables that have some logical relationship
Can contain methods and events
Can support interfaces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

When to choose Struct over the class?

A

CONSIDER a struct instead of a class:
If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

AVOID a struct unless the type has all of the following characteristics:
It logically represents a single value, similar to primitive types (int, double, etc.).
It has an instance size under 16 bytes.
It is immutable. (cannot be changed)
It will not have to be boxed frequently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Does ASP.NET session uses cookies ? If so , what are cookies

A

Yes , ASP.NET used cookies
Cookies : cookies store small amount of information on the client’s machine.Websites use cookies to store user preferences or other information .
Persistent cookies : Even after browser is closed , they live.
Non persistent cookies : Get destroyed once browser is closed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is garbage collection?

A

garbage collector (GC) serves as an automatic memory manager. The garbage collector manages the allocation and release of memory(managed heap) for an application.
To optimize the performance of the garbage collector, the managed heap is divided into three generations, 0, 1, and 2, so it can handle long-lived and short-lived objects separately.
For most of the objects your application creates, you can rely on garbage collection to perform the necessary memory management tasks automatically. However, unmanaged resources require explicit cleanup.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What are unmanaged objects that need manual garbage collection ?

A

The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file handle, window handle, or network connection. Although the garbage collector can track the lifetime of a managed object that encapsulates an unmanaged resource, it doesn’t have specific knowledge about how to clean up the resource.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

How to implement garbage collection on unmanaged objects

A

By Using IDisposable Interface and implementing
Dispose() and DisposeAsync() methods

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Mention some .NET Performance Tips

A

It is best to avoid using value types in situations where they must be boxed a high number of times as it is costly operation converting value to reference as each time , object needs to be created.
Use StringBuilder instead of strings , as they create more temporary strings
Empty finalizers should not be used. When a class contains a finalizer, an entry is created in the Finalize queue. When the finalizer is called, the garbage collector is invoked to process the queue. If the finalizer is empty, this simply results in a loss of performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

what is Keyword ref in C#?

A

ref - ref is used to state that the parameter passed may be modified by the method.
Inside a method If a reference type is assigned to a new object, that change will be local to that method. If the same reference is accessed outside the method, the object remains in the same form before how it was sent to the method
In order for the reference object to be modified, the ref should be used along with the type when it is sent to the method.

34
Q

what is keyword out in c#?

A

out - out is used to state that the parameter passed must be modified by the method
out can be both value type and reference type
If it is a reference type, it will be initialized to NULL.
If it is a value type, it should be initialized?
Out should be compulsorily modified or initialized inside the method to which it is sent to.

35
Q

what is Keyword ‘in’ in C#?

A

The in modifier is most often used for performance reasons and was introduced in C# 7.2.
The motivation of ‘in’ is to be used with a struct to improve performance by declaring that the value will not be modified.
When using reference types, it only prevents you from assigning a new reference.

36
Q

Are modifiers in , out , ref allowed on all methods?

A

in, out, and ref cannot be used in methods with the async modifier.

37
Q

Is it possible to Overload Methods with Modifiers?

A

When overloading a method in C#, using a modifier will be considered a different method signature than not using a modifier at all.
You cannot overload a method if the only difference between methods is the type of modifier used. This will result in a compile error.

38
Q

Why use getters and setters in C#?

A

Basically getters and setters are just means of helping encapsulation.
When you make a class you have several class variables that perhaps you want to expose to other classes to allow them to get a glimpse of some of the data you store. While just making the variables public to begin with may seem like an acceptable alternative, in the long run you will regret letting other classes manipulate your classes member variables directly.
If you force them to do it through a setter, you can add logic to ensure no strange values ever occur, and you can always change that logic in the future without effecting things already manipulating this class.

Example:

public string Name { get; set; }

is similar to

private string _name;
public string getName { return _name; }
public void setName(string value) { _name = value; }

39
Q

What are different cache techniques used in .NET core ?

A

ASP.NET Core uses two caching techniques.
In-memory caching uses the server memory to store cached data locally, and distributed caching distributes the cache across various servers.

40
Q

What is InMemory cache ?

A

The simplest cache implementation in ASP.NET Core is represented by IMemoryCache. It runs in-process, so it’s fast.

A disadvantage of this single process model is that the cache data isn’t shared horizontally across scaled-out instances of the application. Because of this limitation, it’s best suited for single-server deployments.

41
Q

What is distributed cache?

A

A distributed cache runs independently of any single ASP.NET Core app process, so all running instances of your web app can share cached data. This ensures that data survive individual web app restarts and that the data is consistent between all web apps.

42
Q

What is session cache ?

A

ASP.NET Core’s Session cache is similar to the caching options we’ve already discussed. But there’s one significant difference: the data it stores is private to the user making the current web request, not shared among all users.

43
Q

What types of Caching are available in ASP.NET?

A

Page Caching, Fragment Caching, and Data Caching

44
Q

What is page caching and how it is done ?

A

To cache an entire page’s output we need to specify a action attribute at the top of our page, this attribute is the @ OutputCache .by using the output cache action filter attribute

45
Q

what is Fragment caching and how it is done?

A

In some scenarios we only need to cache only a segment of a page. For example a contact us page in a main page will be the same for all the users and for that there is no need to cache the entire page.

So for that we prefer to use fragment caching option.

46
Q

What is Data caching ?

A

ASP.NET supports data caching by treating them as small sets of objects. We can store objects in memory very easily and use them depending on our functionality and needs, anywhere across the page.

47
Q

How to do output caching in c#?

A

To manually cache application data, you can use the MemoryCache class in ASP.NET.
ASP.NET also supports output caching, which stores the generated output of pages, controls, and HTTP responses in memory.
You can configure output caching declaratively in an ASP.NET Web page or by using settings in the Web.config file

48
Q

What are the different types of authorizations in ASP.NET Core?

A

Different types of Authorization are
1.Simple authorization
2.Role-based authorization
3.claims-based authorization
4.policy-based authorization

49
Q

What is simple authorization ?

A

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users.
It checks if the user is logged in or not and based on that provide access

50
Q

How to Manage roles in ASP.net core?

A

Using the Role Manager class that implements IdentityRole, different roles can be managed.
By using DI, this is made available to different modules and classes in the solution

51
Q

How to Manage users in ASP.net core?

A

Using UserManager class that implements IdentityUser, different users can be managed

52
Q

What is claim-based authorization?

A

A claim is a name and value pair.It is really a piece of information about the user . It is not about what a user or cannot do . It is about how you use this information to make authorization . For example if an employee applies for a maternity leave , we check for the gender etc

53
Q

What is policy based authorization?

A

We include one or more claims to create the policy and then use those policies for authorization

54
Q
A

In ASP.NET a Role is a claim with Type Role

55
Q

What is Managed vs Unmanaged Code in .NET?

A

Managed Code - It is executed by managed runtime environment or managed by the CLR.

Unmanaged Code -It is executed directly by the operating system.

56
Q

What is the Difference between Managed code vs UnManaged Code in terms of GC ?

A

Managed Code : Memory is managed by CLR’s Garbage Collector.

UnManaged Code : Memory is managed by the programmer.

57
Q

What does ‘await’ do?

A

Await provides a non-blocking way to start a task and then continue execution when the task completes . During this entire time , main thread is available to take on requests

58
Q

How to run multiple tasks or methods at the sametime

A

By creating async methods that return tasks . Remember async method should have await statement inside it

59
Q

How does project reference in .net gets resolved ?

A

If the referenced project is part of same solution and is set to build , published project will include the compiled output (dll) of referenced project

60
Q

What is Task?

A

Task is recommended return type for
Async method . An async method can have Task - returns no value , Task<T> or void - for event handler as its return type</T>

61
Q

What is ‘??’

A

Null-coalescing operator ?? returns the value of its left-hand operand if it isn’t null ; otherwise , it evaluates the right-hand operand and returns its result. The ‘??’ doesn’t evaluate rh if lh is not null

62
Q

What is ‘??=‘

A

Null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operator evaluates to null. The ‘??=‘ operator doesn’t evaluate its rh if lh is not null

63
Q

What is the difference between button type = ‘submit’ and regular button in .net

A

a button with type=’submit’ is typically used for triggering form submissions, while a regular button requires explicit handling in code and won’t automatically submit a form.

64
Q

What happens when you click on button type = submit on a form?

A

In web development, you usually define the form’s action attribute to specify the URL to which the form data is sent upon submission. The server-side code at that URL processes the data and determines the subsequent action or response.

65
Q

What is ‘using’ keyword used for?

A

Using is used to ensure that an object is properly disposed of when it no longer needed. It is commonly used with types that implement IDisposable interface

66
Q

What is await keyword?

A

Await keyword is used asynchronously to wait for the completion of task or operation. It allows the program to continue executing other code while waiting for awaited task to finish

67
Q

What is await using ?

A

Await using statement allows for asynchronous disposal of an object. It is typically used with types that implement IAsyncDisposable interface

68
Q

Is it possible to split the definition of class or interface or method over two or more source files?

A

Using partial modifier we can split but the modifier should be same for the files

69
Q

When to use HTTP trigger azure function vs web api

A

If there are sudden spikes in consumption then azure function will give you better scalability

70
Q

What is modeling the database in EF?

A

Modeling is EF Core’s wat of working out what the db looks like by looking at the classes and other EF core configuration data

71
Q

What is ?. Operator- null conditional operator?

A

It checks if the object is not null before method is called . If object is null, the method is not called . If used against properties or methods that return a value, compiler throws an error if the object is null

72
Q

What is ?[] - Null conditional operator?

A

It is used to access an element from a list of nullable elements. If the list is null, it returns null else the element is returned , provided the list is not empty. If empty , then you get index out of range exception which needs to be handled anyway for nullable or non nullable list

73
Q

What is configureAwait?

A

It determines whether the task should continue in the same or different context as the one that started task

74
Q

What is a context?

A

Context is an abstraction that represents some state or environment associated with a thread of execution. For example in UI app, UI thread and message loop . In an ASP.NET application, context is HTTP request and its associated state

75
Q

What is the default behavior of await?

A

Default behavior of await is to capture the current context when the task is started and resumen the continuation in the same context when the task is completed. This ensures that the continuation can access the same state and resources as the original code

76
Q

What problems occur with default behavior of await?

A

Deadlocks , performance , scalability

77
Q

Deadlock issue with running on same thread

A

If captured context is blocked by another operation that depends on completion of current task, a deadlock can occur.

78
Q

Performance issue with running on same thread?

A

Resuming the continuation on the same context that started the task can cause unnecessary context switches and delays

79
Q

Scalability issue with running in same context?

A

If captured context had a limited capacitu for processing operations, resuming too many continuations on that context can exhaust its resources and degrade its responsiveness

80
Q

Do we need to explicitly mention to consider appsettings.json to use in program.cs for netcore 2.0 app?

A

Not required by using webhostbuilder, default configuration uses appsettings.json

81
Q

Do we need to explicitly mention to consider appsettings.json to use in program.cs for netcore 2.0 app?

A

Not required by using webhostbuilder, default configuration uses appsettings.json