Method Overriding
Overriding allows a subclass to provide a specific implementation of a method already defined in its parent class.
public class BaseClass
{
public virtual void Show() => Console.WriteLine("Base Class");
}
public class DerivedClass : BaseClass
{
public override void Show() => Console.WriteLine("Derived Class");
}
2. Static Class and Methods
Static Class: Can’t be instantiated. Used for utility or helper methods.
public static class MathOperations
{
public static int Add(int a, int b) => a + b;
}
3. Inheritance
Allows a class to inherit methods and properties from another class.
public class Animal { public void Eat() { Console.WriteLine("Eating"); } }
public class Dog : Animal { public void Bark() { Console.WriteLine("Barking"); } }
4. Lock in Multi-threading
Used to ensure that one thread doesn't access critical sections of code while another thread is still executing it.
private static readonly object _lock = new object();
public void ThreadSafeMethod()
{
lock (_lock)
{
// Critical section of code
}
}
5. Process and Thread Difference
Process: An independent program running in its own memory space.
Thread: A unit of execution within a process.
6. Filters in ASP.NET MVC
Filters are attributes that execute code before or after certain stages in the request processing pipeline.
[Authorize] // Authorization Filter
public class HomeController : Controller
{
public IActionResult Index() { }
}
7. Exception Handling
Using try-catch-finally to handle exceptions.
try { int result = 10 / 0; }
catch (DivideByZeroException ex) { Console.WriteLine("Error: " + ex.Message); }
finally { Console.WriteLine("Cleanup code here"); }
8. Extension Methods
Static methods that allow adding new functionalities to existing types without modifying them.
public static class StringExtensions
{
public static bool IsPalindrome(this string str)
{
return str == new string(str.Reverse().ToArray());
}
}
9. Palindrome Program
string input = "madam";
bool isPalindrome = input.SequenceEqual(input.Reverse());
10. Fibonacci Series Program
int n = 10, a = 0, b = 1;
Console.Write($"{a} {b} ");
for (int i = 2; i < n; i++)
{
int temp = a + b;
Console.Write(temp + " ");
a = b;
b = temp;
}
11. Searching Program (Linear Search)
int[] arr = { 1, 3, 5, 7 };
int key = 5;
int index = Array.FindIndex(arr, x => x == key);
12. Sorting Program (Bubble Sort)
int[] arr = { 5, 2, 9, 1 };
for (int i = 0; i < arr.Length - 1; i++)
for (int j = 0; j < arr.Length - i - 1; j++)
if (arr[j] > arr[j + 1])
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
13. File Handling in C#
using System.IO;
File.WriteAllText("file.txt", "Hello World");
string content = File.ReadAllText("file.txt");
14. CRUD Operations in ASP.NET Core
Create: Add data to the database.
Read: Fetch data.
Update: Modify data.
Delete: Remove data.
[HttpPost]
public IActionResult CreateEmployee(Employee employee) { /* Add to DB */ }
15. Armstrong Number Program
int number = 153, sum = 0, temp = number;
while (temp != 0)
{
int digit = temp % 10;
sum += Math.Pow(digit, 3);
temp /= 10;
}
bool isArmstrong = sum == number;
16. PAN Number Validation
string pan = "ABCDE1234F";
bool isValid = Regex.IsMatch(pan, @"^[A-Z]{5}[0-9]{4}[A-Z]$");
17. Alphabet Count in a Sentence
string sentence = "Hello World";
int letterCount = sentence.Count(char.IsLetter);
18. Collection Types with Examples
List: Dynamic array
Dictionary: Key-value pairs
List<int> numbers = new List<int>() { 1, 2, 3 };
Dictionary<string, string> dict = new Dictionary<string, string> { {"Key1", "Value1"} };
19. Web API vs WCF
Web API: RESTful, lightweight, ideal for HTTP-based services.
WCF: Supports SOAP and other protocols, more complex.
20. Cross-Origin in Web API (CORS)
Used to allow or block requests from different domains.
services.AddCors(options => {
options.AddPolicy("AllowAll", builder => {
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});
21. Alias Naming
You can alias a namespace or a class to avoid conflicts.
using ProjectA = NamespaceA.ClassA;
22. Attribute Routing in Web API
[Route("api/employees/{id}")]
public IActionResult GetEmployee(int id) { /* Get employee by id */ }
23. Media Type Formatters in Web API
Handles converting data to specific formats like JSON or XML.
24. Web API Authentication and Authorization Flow
Use JWT Tokens or OAuth for securing API endpoints.
Authentication: Verifies user identity.
Authorization: Determines access levels based on roles.
25. OOP Concepts in C#
Encapsulation: Data hiding.
Inheritance: Reuse base class functionality.
Polymorphism: Multiple forms of a method (method overloading/overriding).
Abstraction: Hide complex implementation details.
26. Class vs Structure
Class: Reference type, supports inheritance, can be null.
Struct: Value type, no inheritance, cannot be null.
27. Object as Reference
When passed to a method, objects are passed by reference, allowing modification of original data.
28. Abstract Class vs Class
Abstract class is a base class that can't be instantiated and may contain abstract methods.
29. Polymorphism - Overloading & Overriding
Overloading: Multiple methods with the same name but different parameters.
Overriding: Derived class redefines the base class method.
30. Abstraction vs Encapsulation
Abstraction: Hides the implementation.
Encapsulation: Protects data by hiding it.
31. Abstract Class vs Interface
Abstract Class: Can have concrete methods.
Interface: Only has method declarations, no concrete implementation.
32. Implicit vs Explicit Interface Implementation
public interface ITest { void Show(); }
public class MyClass : ITest
{
void ITest.Show() { } // Explicit implementation
}
33. Sealed Class & Method
Sealed Class: Prevents inheritance.
Sealed Method: Prevents overriding in derived classes.
34. ExpandoObject
Used to add properties dynamically at runtime.
dynamic obj = new ExpandoObject();
obj.Name = "John";
35. Static, Virtual & Override
Static: Method belongs to the class.
Virtual: Allows overriding in derived classes.
Override: Replaces base class implementation.
36. Dynamic vs Var
Var: Type is determined at compile-time.
Dynamic: Type is determined at runtime.
Nullable Types
Nullable types allow value types to be assigned null.
int? nullableInt = null;
if (nullableInt.HasValue)
{
Console.WriteLine(nullableInt.Value);
}
else
{
Console.WriteLine("No value assigned");
}
out and ref
out and ref are used to pass arguments by reference.
void ExampleOut(out int number)
{
number = 10; // Must be assigned before method ends
}
void ExampleRef(ref int number)
{
number += 10; // Can be used without assignment
}
int a;
ExampleOut(out a); // a is now 10
int b = 5;
ExampleRef(ref b); // b is now 15
const vs readonly
const is a compile-time constant, while readonly is a runtime constant.
public class Example
{
public const int ConstValue = 10;
public readonly int ReadOnlyValue;
public Example(int value)
{
ReadOnlyValue = value; // Can only be assigned in constructor
}
}
Multicast Delegates
Multicast delegates can point to multiple methods.
public delegate void Notify();
public class MulticastExample
{
public static void Method1() => Console.WriteLine("Method1");
public static void Method2() => Console.WriteLine("Method2");
public static void Main()
{
Notify notify = Method1;
notify += Method2;
notify(); // Calls both Method1 and Method2
}
}
Jagged Array
A jagged array is an array of arrays.
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
Singleton Implementation
Singleton ensures a class has only one instance.
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Delegate
A delegate is a type that represents references to methods.
public delegate void DisplayMessage(string message);
public class DelegateExample
{
public static void ShowMessage(string message)
{
Console.WriteLine(message);
}
public static void Main()
{
DisplayMessage display = ShowMessage;
display("Hello, World!");
}
}
Boxing and Unboxing
Boxing converts a value type to an object type, and unboxing extracts the value type from the object.
int num = 123;
object boxed = num; // Boxing
int unboxed = (int)boxed; // Unboxing
throw vs throw ex
throw preserves the original stack trace, while throw ex resets it.
try
{
// Some code
}
catch (Exception ex)
{
throw; // Preserves stack trace
// throw ex; // Resets stack trace
}
Can Multiple Catch Blocks Execute?
No, only the first matching catch block executes.
try
{
// Some code
}
catch (ArgumentException ex)
{
// Handle ArgumentException
}
catch (Exception ex)
{
// Handle other exceptions
}
Serialization
Serialization converts an object to a format that can be stored or transmitted.
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class SerializationExample
{
public static void Main()
{
Person person = new Person { Name = "John", Age = 30 };
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream("person.bin", FileMode.Create, FileAccess.Write))
{
formatter.Serialize(stream, person);
}
}
}
Dependency Injection
Dependency Injection is a design pattern for managing dependencies.
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve() => Console.WriteLine("Service Called");
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void Start() => _service.Serve();
}
public class Program
{
public static void Main()
{
IService service = new Service();
Client client = new Client(service);
client.Start();
}
}
async and await
async and await are used for asynchronous programming.
public async Task<string> GetDataAsync()
{
await Task.Delay(1000); // Simulate async work
return "Data";
}
public async Task MainAsync()
{
string data = await GetDataAsync();
Console.WriteLine(data);
}
Constructor Multicasting
Constructor multicasting isn’t a standard term, but you might be referring to calling multiple constructors.
public class Example
{
public Example() : this(0) { }
public Example(int value)
{
Console.WriteLine(value);
}
}
Reflection
Reflection allows inspection of metadata and dynamic invocation.
Type type = typeof(String);
MethodInfo method = type.GetMethod("Substring", new[] { typeof(int), typeof(int) });
string result = (string)method.Invoke("Hello, World!", new object[] { 7, 5 });
Console.WriteLine(result); // Output: World
Generics
Generics allow type-safe data structures.
public class GenericExample<T>
{
private T data;
public GenericExample(T value)
{
data = value;
}
public T GetData() => data;
}
public class Program
{
public static void Main()
{
GenericExample<int> example = new GenericExample<int>(5);
Console.WriteLine(example.GetData());
}
}
Design Patterns
Commonly asked design patterns include Singleton, Factory, Observer, and Strategy.
// Example of Factory Pattern
public interface IProduct
{
void DoWork();
}
public class ConcreteProduct : IProduct
{
public void DoWork() => Console.WriteLine("ConcreteProduct is working");
}
public class Factory
{
public IProduct CreateProduct() => new ConcreteProduct();
}
public class Program
{
public static void Main()
{
Factory factory = new Factory();
IProduct product = factory.CreateProduct();
product.DoWork();
}
}
View Encapsulation in Angular
View encapsulation determines whether the styles defined in a component affect the whole application or just the component itself.
TypeScript
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.Emulated // Options: Emulated, None, ShadowDom
})
export class AppComponent {}
Shadow Box in Angular
To apply a shadow box in Angular, you can use the box-shadow CSS property.
HTML
<div class="shadow-box">Content</div>
CSS
.shadow-box {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}
ViewChild and ViewChildren
ViewChild and ViewChildren are used to access child components or DOM elements.
TypeScript
import { Component, ViewChild, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>Child Component</p>'
})
export class ChildComponent {}
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
<app-child></app-child>
`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) singleChild: ChildComponent;
@ViewChildren(ChildComponent) multipleChildren: QueryList<ChildComponent>;
ngAfterViewInit() {
console.log(this.singleChild);
this.multipleChildren.forEach(child => console.log(child));
}
}
SwitchMap
switchMap is an RxJS operator used to switch to a new observable.
TypeScript
import { Component } from '@angular/core';
import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-root',
template: '<p>Check console for output</p>'
})
export class AppComponent {
ngOnInit() {
of('Hello').pipe(
switchMap(value => of(`${value} World`))
).subscribe(result => console.log(result)); // Output: Hello World
}
}
HostListener
HostListener is used to listen to DOM events on the host element.
TypeScript
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
template: '<p>Click anywhere</p>'
})
export class AppComponent {
@HostListener('document:click', ['$event'])
onClick(event: Event) {
console.log('Document clicked', event);
}
}
ESLint
ESLint is a tool for identifying and fixing problems in JavaScript code.
# Install ESLint in an Angular project
ng add @angular-eslint/schematics
Event Loop
The event loop is a mechanism that handles asynchronous operations in JavaScript.
JavaScript
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');
// Output: Start, End, Timeout
Callback Function
A callback function is a function passed into another function as an argument.
TypeScript
function fetchData(callback: (data: string) => void) {
setTimeout(() => {
callback('Data received');
}, 1000);
}
fetchData(data => console.log(data)); // Output: Data received
package.json and package-lock.json
package.json contains metadata about the project and its dependencies, while package-lock.json locks the versions of dependencies.
JSON
// package.json
{
"name": "example",
"version": "1.0.0",
"dependencies": {
"lodash": "^4.17.21"
}
}
// package-lock.json
{
"name": "example",
"version": "1.0.0",
"dependencies": {
"lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDE7XGZ4k+..."
}
}
}
Multithreading in Node.js
Node.js uses worker threads for multithreading.
JavaScript
const { Worker } = require('worker_threads');
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.postMessage('Hello from worker');
`, { eval: true });
worker.on('message', message => console.log(message)); // Output: Hello from worker
Without await in Node.js
Using promises without await.
JavaScript
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
}
fetchData().then(data => console.log(data)); // Output: Data received
Callback, Import, Using
Using callback functions, importing modules, and using statements.
TypeScript
// Callback
function fetchData(callback: (data: string) => void) {
setTimeout(() => {
callback('Data received');
}, 1000);
}
// Import
import { Component } from '@angular/core';
// Using
fetchData(data => console.log(data)); // Output: Data received
Authentication
Authentication is the process of verifying the identity of a user.
TypeScript
// Example of JWT Authentication in Angular
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {}
login(credentials: { username: string, password: string }): Observable<any> {
return this.http.post('/api/auth/login', credentials);
}
}
What is npm and package.json
npm is a package manager for JavaScript, and package.json is a file that contains metadata about the project and its dependencies.
JSON
// package.json
{
"name": "example",
"version": "1.0.0",
"dependencies": {
"lodash": "^4.17.21"
}
}
Which Compiler
TypeScript uses the TypeScript compiler (tsc).
# Install TypeScript
npm install -g typescript
# Compile TypeScript file
tsc example.ts
Why TypeScript in Angular
TypeScript provides static typing, which helps catch errors at compile time.
TypeScript
let message: string = 'Hello, TypeScript';
console.log(message);
Exception Handling in Stored Procedure
Handling exceptions in SQL stored procedures.
SQL
CREATE PROCEDURE ExampleProcedure
AS
BEGIN
BEGIN TRY
-- Your SQL code here
END TRY
BEGIN CATCH
-- Handle error here
PRINT ERROR_MESSAGE();
END CATCH
END
Using TypeScript to JavaScript
Transpiling TypeScript to JavaScript.
TypeScript
// TypeScript
let message: string = 'Hello, TypeScript';
console.log(message);
// JavaScript (after transpiling)
var message = 'Hello, TypeScript';
console.log(message);
Authentication in C#
Example of authentication in C# using ASP.NET Core.
public class AuthController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public AuthController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[HttpPost("login")]
public async Task<IActionResult> Login(LoginModel model)
{
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false);
if (result.Succeeded)
{
return Ok();
}
return Unauthorized();
}
}
Max Memory for Lambda
The maximum memory allocation for AWS Lambda is 10 GB.
Trigger Lambda without API Gateway
You can trigger AWS Lambda using S3 events, DynamoDB streams, SNS, SQS, and more.
How is Angular Loading
Angular uses a module loader to load modules dynamically.
Private Interface
Interfaces cannot be private in TypeScript.
Composition of Token
Tokens in authentication can include header, payload, and signature.
Abstract and Interface
Abstract classes can have implementations, interfaces cannot.
Sealed Class
A sealed class cannot be inherited.
Constant and Readonly
const is a compile-time constant, readonly is a runtime constant.
SOLID Principles
SOLID principles are a set of design principles for software development.
Ref and Out
ref and out are used to pass arguments by reference in C#.
Interface
An interface defines a contract that implementing classes must follow.
Cluster and Non-Cluster Index
Clustered index sorts the data, non-clustered index does not.
Views in SQL and ADO.NET
Views are virtual tables in SQL, ADO.NET is a data access technology.
Entity Framework
Entity Framework is an ORM for .NET.
Can We Declare Private Interface
No, interfaces cannot be private.
Main.ts in Angular
main.ts is the entry point of an Angular application.
Difference Between Structure and Class
Structs are value types, while classes are reference types.
Structs are stored on the stack, whereas classes are stored on the heap.
Structs cannot inherit from other structs or classes, but they can implement interfaces.
Classes support inheritance.
C#
struct MyStruct
{
public int X;
public int Y;
}
class MyClass
{
public int X;
public int Y;
}
Abstract Class
An abstract class cannot be instantiated and is designed to be inherited by subclasses that implement its abstract methods.
C#
public abstract class Animal
{
public abstract void MakeSound();
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
Sealed Class
A sealed class cannot be inherited.
C#
public sealed class SealedClass
{
public void Display()
{
Console.WriteLine("This is a sealed class.");
}
}
Static in C#
Static members belong to the type itself rather than to a specific object.
C#
public static class Utility
{
public static void DisplayMessage(string message)
{
Console.WriteLine(message);
}
}
Angular Component Lifecycle
Angular components have several lifecycle hooks:
TypeScript
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-example',
template: '<p>Example Component</p>'
})
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
Where to Declare Constants
Constants are declared using the const keyword and must be initialized at the time of declaration.
C#
public class Example
{
public const int MaxValue = 100;
}
Child Module in Angular
Child modules are feature modules that are imported into the root module or other feature modules.
TypeScript
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildComponent } from './child.component';
@NgModule({
declarations: [ChildComponent],
imports: [CommonModule]
})
export class ChildModule {}
Cluster Module in Angular
Cluster modules are not a standard Angular concept but can refer to modules that handle clustering logic, such as marker clustering in maps.
Docker
Docker is a platform for developing, shipping, and running applications in containers.
# Dockerfile example
FROM node:14
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["node", "index.js"]
Jenkins
Jenkins is an open-source automation server used for continuous integration and continuous delivery (CI/CD).
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
stage('Test') {
steps {
echo 'Testing...'
}
}
stage('Deploy') {
steps {
echo 'Deploying...'
}
}
}
}
Sanitization in Angular
Sanitization in Angular is used to prevent security vulnerabilities like XSS attacks.
TypeScript
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-sanitizer',
template: '<div [innerHtml]="safeHtml"></div>'
})
export class SanitizerComponent {
safeHtml: SafeHtml;
constructor(private sanitizer: DomSanitizer) {
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml('<p>Safe HTML</p>');
}
}
Section and Article
<section> and <article> are HTML5 semantic elements used to structure content.
HTML
<section>
<h1>Section Title</h1>
<p>Section content...</p>
</section>
<article>
<h2>Article Title</h2>
<p>Article content...</p>
</article>
No Cache and Local Storage
Local storage is used to store data on the client side.
JavaScript
// Set item
localStorage.setItem('key', 'value');
// Get item
let value = localStorage.getItem('key');
Web Storage
Web storage includes localStorage and sessionStorage.
JavaScript
// localStorage persists until explicitly deleted
localStorage.setItem('key', 'value');
// sessionStorage persists only for the session
sessionStorage.setItem('key', 'value');
Web Worker
Web workers allow you to run scripts in background threads.
JavaScript
// worker.js
self.onmessage = function(e) {
self.postMessage('Worker received: ' + e.data);
};
// main.js
let worker = new Worker('worker.js');
worker.onmessage = function(e) {
console.log(e.data);
};
worker.postMessage('Hello, worker!');
Early Binding and Late Binding
Early binding refers to compile-time binding, while late binding refers to runtime binding.
Schematic Element in HTML
Schematic elements are not a standard HTML concept but could refer to custom elements or components.
ForChild
forChild is used in Angular routing to define child routes.
TypeScript
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{ path: 'child', component: ChildComponent }
]
}
];
Lazy Loading
Lazy loading in Angular loads modules only when needed.
TypeScript
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
Iframe
An <iframe> is used to embed another HTML page within the current page.
HTML
<iframe src="https://example.com" width="600" height="400"></iframe>
Selector in CSS
Selectors are used to select HTML elements for styling.
CSS
/* Class selector */
.class-name {
color: blue;
}
/* ID selector */
#id-name {
color: red;
}
Global Selector
The global selector (*) selects all elements.
CSS
* {
margin: 0;
padding: 0;
}
End Tag Not Needed in HTML
Some HTML elements do not require end tags, like <img> and <br>.
HTML
<img src="image.jpg" alt="Image">
<br>
Responsive Application
Responsive design ensures that applications work on various screen sizes.
CSS
@media (max-width: 600px) {
.container {
flex-direction: column;
}
}
Authentication Interceptor
An authentication interceptor in Angular intercepts HTTP requests to add authentication tokens.
TypeScript
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = 'your-auth-token';
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
return next.handle(authReq);
}
}
Angular Security
Angular provides built-in security features like sanitization and HTTP interceptors.
Session Management
Session management involves maintaining user sessions, often using cookies or tokens.
JSON Not Proper in Node.js Validate
Use a JSON schema validator like ajv to validate JSON.
JavaScript
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
};
const validate = ajv.compile(schema);
const data = { name: 'John', age: 30 };
if (validate(data)) {
console.log('Valid!');
} else {
console.log('Invalid:', validate.errors);
}
NoSQL vs DynamoDB
DynamoDB is a NoSQL database service provided by AWS.
Div and Span in Same Line
Use CSS to display <div> and <span> elements inline.
CSS
div, span {
display: inline-block;
}
Concurrent 4 API
Use Promise.all to handle multiple API calls concurrently.
JavaScript
Promise.all([
fetch('/api/endpoint1'),
fetch('/api/endpoint2'),
fetch('/api/endpoint3'),
fetch('/api/endpoint4')
]).then(responses => {
return Promise.all(responses.map(response => response.json()));
}).then(data => {
console.log(data);
});
Promise.all
Promise.all waits for all promises to resolve.
JavaScript
Promise.all([promise1, promise2]).then(values => {
console.log(values);
});
Node.js Run
Run a Node.js application using node.
node app.js
Difference Between Tuple and Dictionary
Tuples are ordered collections of elements, while dictionaries are key-value pairs.
Python
# Tuple
t = (1, 2, 3)
# Dictionary
d = {'key1': 'value1', 'key2': 'value2'}
Tuple
A tuple is an immutable, ordered collection of elements.
Python
t = (1, 2, 3)
Difference Between Interface and Abstract Class
Interface: Defines a contract with no implementation. Classes implementing the interface must provide the implementation.
Abstract Class: Can have both abstract methods (without implementation) and concrete methods (with implementation). Used when classes share a common base but also need to provide specific implementations.
C#
public interface IAnimal
{
void MakeSound();
}
public abstract class Animal
{
public abstract void MakeSound();
public void Sleep()
{
Console.WriteLine("Sleeping");
}
}
public class Dog : Animal, IAnimal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
Types of Constructors
Default Constructor: No parameters.
Parameterized Constructor: Takes parameters.
Copy Constructor: Initializes an object using another object of the same class.
Static Constructor: Initializes static members of the class.
Private Constructor: Prevents the class from being instantiated.
C#
public class Example
{
public int X;
public int Y;
// Default Constructor
public Example() { }
// Parameterized Constructor
public Example(int x, int y)
{
X = x;
Y = y;
}
// Copy Constructor
public Example(Example example)
{
X = example.X;
Y = example.Y;
}
// Static Constructor
static Example()
{
Console.WriteLine("Static Constructor");
}
// Private Constructor
private Example(string message)
{
Console.WriteLine(message);
}
}
Difference Between Normal and Static Constructor
Normal Constructor: Initializes instance members and is called when an instance of the class is created.
Static Constructor: Initializes static members and is called only once, before any instance is created or any static members are referenced.
C#
public class Demo
{
public int InstanceValue;
public static int StaticValue;
// Normal Constructor
public Demo()
{
InstanceValue = 10;
}
// Static Constructor
static Demo()
{
StaticValue = 20;
}
}
Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon.
C#
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow");
}
}
public class Program
{
public static void Main()
{
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound(); // Output: Bark
myCat.MakeSound(); // Output: Meow
}
}
Overloading in TypeScript
Function overloading allows multiple function signatures for a single function implementation.
TypeScript
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}
console.log(add(1, 2)); // Output: 3
console.log(add("Hello, ", "World!")); // Output: Hello, World!
Cancelled Promise
Promises in JavaScript cannot be directly cancelled, but you can use AbortController to cancel an asynchronous operation.
JavaScript
const controller = new AbortController();
const signal = controller.signal;
fetch('https://jsonplaceholder.typicode.com/todos/1', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', err);
}
});
// Cancel the fetch request
controller.abort();
How Dependency Injection Works Internally
Dependency Injection (DI) in C# involves injecting dependencies into a class through its constructor, properties, or methods. The DI container manages the lifecycle and resolution of these dependencies.
C#
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve() => Console.WriteLine("Service Called");
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void Start() => _service.Serve();
}
public class Program
{
public static void Main()
{
var service = new Service();
var client = new Client(service);
client.Start();
}
}
Project Architecture
Project architecture defines the structure and interaction of components within a software system. It includes layers like presentation, business logic, and data access.
Full-Text Search in SQL
Full-text search allows querying textual data in SQL databases using indexes.
SQL
CREATE FULLTEXT CATALOG MyCatalog;
CREATE FULLTEXT INDEX ON MyTable (MyColumn) KEY INDEX PK_MyTable;
SELECT * FROM MyTable WHERE CONTAINS(MyColumn, 'search term');
Static Constructor and Its Use
A static constructor initializes static members of a class and is called only once.
C#
public class Example
{
static Example()
{
Console.WriteLine("Static Constructor Called");
}
}
Can We Have Parameterized Static Constructor?
No, static constructors cannot have parameters.
Extension Method
Extension methods add new methods to existing types without modifying them.
C#
public static class StringExtensions
{
public static string Reverse(this string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
public class Program
{
public static void Main()
{
string example = "Hello";
Console.WriteLine(example.Reverse()); // Output: olleH
}
}
Caching in C#
Caching improves performance by storing frequently accessed data.
C#
public class CacheExample
{
private static readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
public void SetCache(string key, object value)
{
_cache.Set(key, value, TimeSpan.FromMinutes(10));
}
public object GetCache(string key)
{
return _cache.TryGetValue(key, out var value) ? value : null;
}
}
LINQ
LINQ (Language Integrated Query) allows querying collections in a readable and concise manner.
C#
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Hashtable and Dictionary Difference and Which is Faster
Hashtable: Non-generic, thread-safe for single writer and multiple readers.
Dictionary: Generic, not thread-safe, faster due to type safety.
C#
Hashtable hashtable = new Hashtable();
Dictionary<int, string> dictionary = new Dictionary<int, string>();
HashSet
A HashSet is a collection of unique elements.
C#
HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 };
Design Patterns
Common design patterns include Singleton, Factory, Observer, and Strategy.
Real-Time Scenario of Where to Use Interface and Abstract Classes
Interface: Use when multiple classes need to implement the same set of methods.
Abstract Class: Use when classes share common behavior but also have specific implementations.
Program: Do String Permutation and Split It into Equal Parts
C#
public static void Permute(string str, int l, int r)
{
if (l == r)
Console.WriteLine(str);
else
{
for (int i = l; i <= r; i++)
{
str = Swap(str, l, i);
Permute(str, l + 1, r);
str = Swap(str, l, i);
}
}
}
public static string Swap(string a, int i, int j)
{
char temp;
char[] charArray = a.ToCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return new string(charArray);
}
Program: Find Index of First Non-Repeating Character
C#
public static int FirstNonRepeatingChar(string s)
{
var dict = new Dictionary<char, int>();
foreach (var c in s)
{
if (dict.ContainsKey(c))
dict[c]++;
else
dict[c] = 1;
}
for (int i = 0; i < s.Length; i++)
{
if (dict[s[i]] == 1)
return i;
}
return -1;
}
Program: Find the Diagonal Sum of 3x3 Array
C#
public static int DiagonalSum(int[,] matrix)
{
int sum = 0;
for (int i = 0; i < 3; i++)
{
sum += matrix[i, i];
sum += matrix[i, 2 - i];
}
return sum;
}
Duck Typing in Angular
Duck typing, or structural typing, is a concept where the type or class of an object is determined by its behavior (methods and properties) rather than its explicit type. In TypeScript, this means that if an object has all the required properties and methods, it can be used where that type is expected, regardless of its actual type.
TypeScript
interface Duck {
quack(): void;
}
class Mallard {
quack() {
console.log("Quack!");
}
}
let duck: Duck = new Mallard(); // This works because Mallard has a quack method
duck.quack(); // Output: Quack!
Difference Between SingleOrDefault and FirstOrDefault
SingleOrDefault: Returns the only element of a sequence, or a default value if the sequence is empty. Throws an exception if more than one element is found.
FirstOrDefault: Returns the first element of a sequence, or a default value if the sequence is empty.
C#
var numbers = new List<int> { 1, 2, 3 };
// SingleOrDefault
var single = numbers.SingleOrDefault(n => n == 2); // Returns 2
var singleNotFound = numbers.SingleOrDefault(n => n == 4); // Returns 0 (default for int)
// FirstOrDefault
var first = numbers.FirstOrDefault(); // Returns 1
var firstNotFound = new List<int>().FirstOrDefault(); // Returns 0 (default for int)
Difference Between Dependency Injection (DI) and Inversion of Control (IoC)
Inversion of Control (IoC): A design principle where the control of object creation and management is transferred from the application to a container or framework.
Dependency Injection (DI): A specific implementation of IoC where dependencies are injected into a class, rather than the class creating the dependencies itself.
How to Do Dependency Injection in Different Classes
Dependency Injection can be done using constructor injection, property injection, or method injection.
C#
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve() => Console.WriteLine("Service Called");
}
public class Client
{
private readonly IService _service;
// Constructor Injection
public Client(IService service)
{
_service = service;
}
public void Start() => _service.Serve();
}
// Usage
var service = new Service();
var client = new Client(service);
client.Start();
Difference Between Attributes and Properties
Attributes: Metadata added to code elements (classes, methods, properties) to provide additional information used by the compiler or runtime.
Properties: Members of a class that provide a flexible mechanism to read, write, or compute the value of a private field.
C#
[Serializable]
public class Example
{
public string Name { get; set; }
}
Is .NET Core Only for Multi-Level Platform?
No, .NET Core is a cross-platform framework that runs on Windows, macOS, and Linux12.
Singleton Design Pattern
The Singleton pattern ensures a class has only one instance and provides a global point of access to it.
C#
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
How to Display Content in Angular
Use content projection with <ng-content> to display content in Angular components.
TypeScript
@Component({
selector: 'app-card',
template: '<div class="card"><ng-content></ng-content></div>'
})
export class CardComponent {}
// Usage
<app-card>
<p>This is projected content</p>
</app-card>
Lazy Loading Concept & How It Works
Lazy loading in Angular loads modules only when needed, reducing the initial load time.
TypeScript
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
Storage of Memory in Call by Value and Call by Reference Type
Call by Value: Copies the actual value of an argument into the formal parameter of the function.
Call by Reference: Copies the reference to the memory location of an argument into the formal parameter.
C#
void CallByValue(int x)
{
x = 100;
}
void CallByReference(ref int x)
{
x = 100;
}
int a = 10;
CallByValue(a); // a remains 10
CallByReference(ref a); // a becomes 100
Project Insight
Project architecture typically includes layers like presentation, business logic, and data access.
Sealed Class
A sealed class cannot be inherited.
C#
public sealed class SealedClass
{
public void Display() => Console.WriteLine("This is a sealed class.");
}
Abstract Class
An abstract class cannot be instantiated and is designed to be inherited by subclasses that implement its abstract methods.
C#
public abstract class Animal
{
public abstract void MakeSound();
}
public class Dog : Animal
{
public override void MakeSound() => Console.WriteLine("Bark");
}
Abstract / Interface Difference
Abstract Class: Can have both abstract and concrete methods.
Interface: Only defines methods and properties without implementation.
Authentication and Authorization in Angular Using JWT Token
Use Angular’s HTTP interceptors to add JWT tokens to requests.
TypeScript
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = 'your-auth-token';
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
return next.handle(authReq);
}
}
Authorization from Web API in .NET Core [Authorize Filter]
Use the [Authorize] attribute to secure Web API endpoints.
C#
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult GetSecureData()
{
return Ok("This is secure data");
}
}
Polymorphism Example
Polymorphism allows methods to do different things based on the object it is acting upon.
C#
public class Animal
{
public virtual void MakeSound() => Console.WriteLine("Animal sound");
}
public class Dog : Animal
{
public override void MakeSound() => Console.WriteLine("Bark");
}
public class Cat : Animal
{
public override void MakeSound() => Console.WriteLine("Meow");
}
public class Program
{
public static void Main()
{
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound(); // Output: Bark
myCat.MakeSound(); // Output: Meow
}
}
Can a Stored Procedure Be Called from a Function?
No, a stored procedure cannot be called from a function in SQL Server.
SQL - Sum of Salary with and Without Using SUM
Using SUM:
SQL
SELECT SUM(Salary) FROM Employees;
Without using SUM:
SQL
SELECT
(SELECT Salary FROM Employees WHERE EmployeeID = 1) +
(SELECT Salary FROM Employees WHERE EmployeeID = 2) +
(SELECT Salary FROM Employees WHERE EmployeeID = 3) AS TotalSalary;
Cursor - Code
A cursor in SQL Server is used to iterate through a result set row by row.
SQL
DECLARE @EmployeeID INT;
DECLARE EmployeeCursor CURSOR FOR
SELECT EmployeeID FROM Employees;
OPEN EmployeeCursor;
FETCH NEXT FROM EmployeeCursor INTO @EmployeeID;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Process each row
FETCH NEXT FROM EmployeeCursor INTO @EmployeeID;
END;
CLOSE EmployeeCursor;
DEALLOCATE EmployeeCursor;
Angular Structure
Angular applications are structured into modules, components, services, and templates.
CLR - How It Works
The Common Language Runtime (CLR) is the virtual machine component of .NET that manages the execution of .NET programs.
Triangle * Print Program
C#
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Show Manager ID with Employee Using Self Join
SQL
SELECT e.EmployeeID, e.EmployeeName, m.EmployeeName AS ManagerName
FROM Employees e
LEFT JOIN Employees m ON e.ManagerID = m.EmployeeID;
Promise / Observable Difference
Promise: Handles a single asynchronous event.
Observable: Handles a stream of asynchronous events.
TypeScript
// Promise
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise resolved'), 1000);
});
// Observable
let observable = new Observable(observer => {
setTimeout(() => {
observer.next('Observable emitted');
observer.complete();
}, 1000);
});
.NET Framework vs .NET Core
.NET Framework: Windows-only, mature, extensive libraries, used for desktop and web applications.
.NET Core: Cross-platform (Windows, macOS, Linux), modern, high performance, modular, used for cloud, IoT, and microservices.
Base Class & Child Class in Depth
A base class (parent) provides common functionality, while a child class (derived) inherits and extends it.
public class Animal
{
public void Eat() => Console.WriteLine("Eating");
}
public class Dog : Animal
{
public void Bark() => Console.WriteLine("Barking");
}
public class Program
{
public static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Inherited method
dog.Bark(); // Child class method
}
}
Dependency Injection (DI) and How to Use It
DI is a design pattern that allows a class to receive its dependencies from an external source rather than creating them itself.
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve() => Console.WriteLine("Service Called");
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void Start() => _service.Serve();
}
// Usage
var service = new Service();
var client = new Client(service);
client.Start();
Triggers in SQL
Triggers are special stored procedures that automatically execute in response to certain events on a table or view.
SQL
CREATE TRIGGER trgAfterInsert
ON Employees
AFTER INSERT
AS
BEGIN
PRINT 'After Insert Trigger Fired'
END;
Delegates in C#
Delegates are type-safe function pointers used to pass methods as arguments.
public delegate void Notify(string message);
public class Program
{
public static void Main()
{
Notify notify = ShowMessage;
notify("Hello, World!");
}
public static void ShowMessage(string message)
{
Console.WriteLine(message);
}
}
Delegates vs Events with Example
Delegates: Directly call methods.
Events: Encapsulate delegates, providing a way to notify subscribers.
public delegate void Notify();
public class EventPublisher
{
public event Notify OnNotify;
public void NotifySubscribers()
{
OnNotify?.Invoke();
}
}
public class Subscriber
{
public void Subscribe(EventPublisher publisher)
{
publisher.OnNotify += () => Console.WriteLine("Notified");
}
}
Generics Explanation
Generics allow you to define classes, methods, and interfaces with a placeholder for the type.
public class GenericClass<T>
{
private T data;
public GenericClass(T value)
{
data = value;
}
public T GetData() => data;
}
Can Generics Be in Interfaces?
Yes, interfaces can be generic.
public interface IRepository<T>
{
void Add(T item);
T Get(int id);
}
How to Avoid Build Errors by Creating Constructors in Generics Class
Ensure the generic type has a parameterless constructor.
public class GenericClass<T> where T : new()
{
private T data;
public GenericClass()
{
data = new T();
}
}
Value Type and Reference Type
Value Type: Stores data directly (e.g., int, struct).
Reference Type: Stores a reference to the data (e.g., class, string).
int valueType = 10; // Value type
string referenceType = "Hello"; // Reference type
Properties and Fields Difference
Fields: Variables declared directly in a class.
Properties: Provide a flexible mechanism to read, write, or compute the value of a private field.
public class Example
{
private int field;
public int Property { get; set; }
}
Can We Create Custom Value Types?
Yes, using struct.
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
Polymorphism of Class Concepts
Polymorphism allows methods to do different things based on the object it is acting upon.
public class Animal
{
public virtual void MakeSound() => Console.WriteLine("Animal sound");
}
public class Dog : Animal
{
public override void MakeSound() => Console.WriteLine("Bark");
}
Async Call and How It Works
Async methods allow for asynchronous programming, improving responsiveness.
public async Task<string> GetDataAsync()
{
await Task.Delay(1000); // Simulate async work
return "Data";
}
Async Call to DB Using Entity Framework
Use async and await with Entity Framework for database operations.
public async Task<List<Employee>> GetEmployeesAsync()
{
using (var context = new MyDbContext())
{
return await context.Employees.ToListAsync();
}
}
Entity Usage in Project
Entity Framework is an ORM that simplifies data access by mapping objects to database tables.
Project Insights - Detailed
Project architecture typically includes layers like presentation, business logic, and data access.
HTTP Methods
Common HTTP methods include GET, POST, PUT, DELETE, PATCH.
Configuration of Angular to API
Configure Angular to communicate with an API using HttpClient.
TypeScript
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('/api/data');
}
}
Where Are Libraries Stored in Angular? Flow?
Libraries are stored in the node_modules folder. Angular uses a module system to manage dependencies.
GET / POST, Update and PATCH Difference - Web API
GET: Retrieve data.
POST: Create new data.
PUT: Update existing data.
PATCH: Partially update existing data.
Microservice Basic Architecture and Flow
Microservices architecture involves breaking down an application into smaller, independent services that communicate over HTTP.
AWS Flow in Application
AWS services like Lambda, S3, and DynamoDB can be used to build scalable applications.
Abstract Methods in Application
Abstract methods are declared in abstract classes and must be implemented by derived classes.
Release/Debug Process
Release builds are optimized for performance, while debug builds include additional debugging information.
Metadata Package
Metadata packages contain information about the structure and content of data.
HTTP Options in .NET Core
HTTP options in .NET Core include configuring middleware, routing, and services.
Idempotent - Which is Idempotent in HTTP Verbs
Idempotent HTTP methods include GET, PUT, DELETE, and OPTIONS, meaning multiple identical requests have the same effect as a single request.
Pure Virtual Class
In C#, the concept of a “pure virtual class” is not directly applicable as it is in C++. However, you can achieve similar functionality using abstract classes and methods. An abstract class in C# can have abstract methods that must be implemented by derived classes.
public abstract class Animal
{
public abstract void MakeSound(); // Abstract method
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
Abstract Method
An abstract method is a method that is declared in an abstract class and does not have an implementation. Derived classes must provide an implementation for the abstract method.
public abstract class Shape
{
public abstract double GetArea(); // Abstract method
}
public class Circle : Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public override double GetArea()
{
return Math.PI * radius * radius;
}
}
Dependency Injection (DI)
Dependency Injection is a design pattern used to implement IoC (Inversion of Control), allowing the creation of dependent objects outside of a class and providing those objects to a class in various ways.
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve() => Console.WriteLine("Service Called");
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void Start() => _service.Serve();
}
// Usage
var service = new Service();
var client = new Client(service);
client.Start();
SOLID Principles
SOLID is an acronym for five design principles intended to make software designs more understandable, flexible, and maintainable:
Single Responsibility Principle (SRP): A class should have only one reason to change.
Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
Interface Segregation Principle (ISP): No client should be forced to depend on methods it does not use.
Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.
Open/Closed Principle (OCP) in Depth
The Open/Closed Principle states that software entities should be open for extension but closed for modification. This can be achieved using interfaces or abstract classes.
public interface IShape
{
double CalculateArea();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public double CalculateArea()
{
return Width * Height;
}
}
public class AreaCalculator
{
public double CalculateArea(IShape shape)
{
return shape.CalculateArea();
}
}
Mixins in WebAPI / Angular
Mixins in TypeScript allow you to create reusable classes that can be combined to form new classes.
TypeScript
type Constructor<T = {}> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
timestamp = new Date();
};
}
class Example {
exampleProperty = "example";
}
const TimestampedExample = Timestamped(Example);
const instance = new TimestampedExample();
console.log(instance.timestamp); // Outputs the current date and time
Versioning in API
API versioning allows you to manage changes to your API without breaking existing clients. Common strategies include URI versioning, query parameter versioning, and header versioning.
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult GetV1() => Ok("Version 1.0");
}
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class MyControllerV2 : ControllerBase
{
[HttpGet]
public IActionResult GetV2() => Ok("Version 2.0");
}
Clustered to Non-Primary Tables
In SQL Server, a clustered index determines the physical order of data in a table. A table can have only one clustered index, which is often created on the primary key. Non-clustered indexes are separate from the data and can be created on non-primary key columns.
SQL
-- Create a clustered index on the primary key
CREATE CLUSTERED INDEX IX_Employees_Id ON Employees(Id);
-- Create a non-clustered index on a non-primary key column
CREATE NONCLUSTERED INDEX IX_Employees_Name ON Employees(Name);
Base and Derived Class, Object of Derived Class Which Constructor Will Be Called
When an object of a derived class is created, the base class constructor is called first, followed by the derived class constructor.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base class constructor");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor");
}
}
// Usage
var obj = new DerivedClass();
// Output:
// Base class constructor
// Derived class constructor
Constructor in Abstract Class? Public Constructor
Abstract classes can have constructors, which are called when an instance of a derived class is created. Public constructors in abstract classes are not recommended because abstract classes cannot be instantiated directly.
public abstract class AbstractClass
{
protected AbstractClass()
{
Console.WriteLine("Abstract class constructor");
}
}
public class ConcreteClass : AbstractClass
{
public ConcreteClass()
{
Console.WriteLine("Concrete class constructor");
}
}
// Usage
var obj = new ConcreteClass();
// Output:
// Abstract class constructor
// Concrete class constructor
Comments
Post a Comment