What is Cross Page Posting in ASP. NET?

Cross Page Posting

Cross Page Posting is a mechanism in ASP.NET that enables a Web Form to post its form data to a different page using the PostBackUrl property.

How Cross Page Posting Works

Page 1 – Source Page

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server"
    Text="Submit"
    PostBackUrl="~/Result.aspx" />

✔ The PostBackUrl specifies the target page.

Page 2 – Target Page

protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null)
    {
        TextBox txtName =
            (TextBox)PreviousPage.FindControl("txtName");

        if (txtName != null)
        {
            string name = txtName.Text;
        }
    }
}

✔ PreviousPage gives access to the source page

✔ FindControl() fetches values from the previous page

Using @PreviousPageType (Strongly Typed – Recommended)

Page 2 (Result.aspx)

<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
protected void Page_Load(object sender, EventArgs e)
{
    string name = PreviousPage.txtName.Text;
}

✔ Type-safe

✔ Cleaner code

✔ Better performance

Difference: PostBack vs Cross Page Posting

FeaturePostBackCross Page Posting
Target pageSame pageDifferent page
Property usedDefault behaviorPostBackUrl
State handlingViewStatePreviousPage
Common useValidationMulti-page forms

When to Use Cross Page Posting

  • ✔ Multi-step forms
  • ✔ Wizard-style pages
  • ✔ Simple data transfer between pages
  • ✔ Avoiding Session usage

Limitations

  • ❌ Only works with ASP.NET Web Forms
  • ❌ Not recommended for large data transfer
  • ❌ Not supported in ASP.NET MVC / Core

Interview Tip

Cross Page Posting is an ASP.NET Web Forms feature that uses the PostBackUrl property to submit form data to another page, accessible via the PreviousPage object.


What is COALESCE and Why use in SQL Server?

Definition 

COALESCE evaluates its arguments from left to right and returns the first expression that is not NULL. If all expressions are NULL, it returns NULL.

Syntax

COALESCE(expression1, expression2, ..., expressionN)

Simple Example

SELECT COALESCE(NULL, NULL, 'SQL Server', 'Database');

Output: SQL Server

Practical Table Example

Table: Employees

EmpIdNameEmail
1Johnjohn@mail.com
2MaryNULL
3AlexNULL

Query:

SELECT 
    Name,
    COALESCE(Email, 'Not Available') AS Email
FROM Employees;

Result:

NameEmail
Johnjohn@mail.com
MaryNot Available
AlexNot Available

Multiple Column Example

SELECT COALESCE(HomePhone, WorkPhone, MobilePhone, 'No Contact') AS ContactNumber FROM Customers;

  • ✔ Returns first available phone number
  • ✔ Avoids NULL values

COALESCE vs ISNULL (Interview Tip)

FeatureCOALESCEISNULL
Standard SQL✅ Yes❌ No
Multiple values✅ Yes❌ No
Data type precedenceHigherFirst argument
PortabilityHighSQL Server only

One-Line Interview Answer

COALESCE is a SQL Server function that returns the first non-NULL value from a list of expressions.


What Are Generics in C#?

Technical Definition 

Generics allow developers to create strongly typed components by specifying type parameters that are replaced with actual data types at compile time.

Why Generics Are Needed

Before generics, collections stored data as object, which caused:

  • Runtime casting errors
  • Boxing and unboxing overhead
  • Poor type safety

Generics solve these problems.

Simple Example (Generic Class)

public class MyGeneric<T>
{
    public T Data { get; set; }
}
MyGeneric<int> obj1 = new MyGeneric<int>();
obj1.Data = 100;

MyGeneric<string> obj2 = new MyGeneric<string>();
obj2.Data = "Hello";
  • ✔ Compile-time type checking
  • ✔ No casting required

Generic Method Example

public void Print<T>(T value)
{
    Console.WriteLine(value);
}
Print<int>(10);
Print<string>("C# Generics");

Generic Collection Example

List<int> numbers = new List<int> { 1, 2, 3 };
List<string> names = new List<string> { "John", "Alex" };
  • ✔ Type safe
  • ✔ Faster than non-generic collections

Generic Constraints

public class Repository<T> where T : class
{
}

Common Constraints

ConstraintDescription
where T : classReference type
where T : structValue type
where T : new()Default constructor
where T : BaseClassInheritance
where T : interfaceInterface implementation

Advantages of Generics

  • ✔ Strong type safety
  • ✔ Reusable code
  • ✔ Better performance
  • ✔ Cleaner, maintainable code

One-Line Interview Answer

Generics in C# allow the creation of type-safe and reusable code by defining placeholders for data types that are specified at runtime or compile time.


What is the difference between STUFF and REPLACE in SQL Server?

SQL Server String Functions

In SQL Server, both STUFF and REPLACE are string functions used to modify text, but they work in very different ways.

1. STUFF Function

Purpose: Deletes a specified number of characters from a string starting at a given position and optionally inserts another string at that position.

Syntax: STUFF(string, start, length, replace_with)

Example:

SELECT STUFF('SQLServer', 4, 6, ' Database');

Output: SQL Database

  • ✔ Position-based
  • ✔ Allows deletion + insertion

2. REPLACE Function

Purpose: Replaces all occurrences of a specified substring with another substring.

Syntax: REPLACE(string, search_string, replace_string)

Example:

SELECT REPLACE('SQL Server Server', 'Server', 'Database');

Output: SQL Database Database

  • ✔ Value-based
  • ✔ Replaces every match

Key Differences

FeatureSTUFFREPLACE
Replacement typePosition-basedText-based
ReplacesFixed charactersAll matching substrings
Occurrence controlSingle locationAll occurrences
Uses indexYes (start position)No
Common useInsert/remove textFind & replace

Real-World Example

Remove First Comma Only (STUFF):

SELECT STUFF(',,100,200', 1, 1, '');

Output: ,100,200

Replace All Commas (REPLACE):

SELECT REPLACE(',,100,200', ',', '');

Output: 100200

🧠 Interview One-Liner

STUFF modifies a string based on character position, whereas REPLACE substitutes all occurrences of a specified substring.


What is TPL in C#?

Task Parallel Library (TPL) in C#

TPL stands for Task Parallel Library in C#. It is a set of public types and APIs in the .NET Framework that simplifies the process of adding parallelism and concurrency to applications.

What is TPL?

The Task Parallel Library (TPL) provides a higher-level abstraction for working with threads and asynchronous programming by using tasks. It helps you write efficient, scalable, and easy-to-maintain parallel code without dealing directly with threads.

Key Features

  • Simplifies multi-threading
  • Supports parallel loops and task-based asynchronous programming
  • Improves performance on multi-core processors
  • Supports cancellation and continuation

Basic Example: Running a Task

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Task task = Task.Run(() =>
        {
            Console.WriteLine("Task is running...");
        });

        task.Wait(); // Wait for the task to complete
        Console.WriteLine("Task completed.");
    }
}

Output

Task is running...
Task completed.

Parallel.For Example

Parallel.For(0, 5, i =>
{
    Console.WriteLine($"Processing item {i} on thread {Task.CurrentId}");
});

Task with Continuation Example

Task.Run(() => {
    Console.WriteLine("First task");
}).ContinueWith(t => {
    Console.WriteLine("Continuation task");
});

Interview One-Liner

TPL is a .NET library that simplifies parallel and asynchronous programming by using tasks and parallel loops instead of raw threads. 


What is Channel Factory C#?

ChannelFactory in C# is a class used in Windows Communication Foundation (WCF) to create channels (proxies) for communicating with a service endpoint without using generated proxy classes. It provides a way to create a client-side channel dynamically at runtime.


✅ What is ChannelFactory?

  • It’s part of System.ServiceModel namespace.

  • It creates a channel (client proxy) to communicate with a WCF service.

  • Allows flexible and dynamic client creation.

  • Useful when you don’t want to use Add Service Reference or auto-generated proxies.


🔹 Basic Use Case

You define a service contract interface and then create a channel to call the service.


🔹 Example

1. Define the Service Contract

[ServiceContract] public interface ICalculator { [OperationContract] int Add(int a, int b); }

2. Create ChannelFactory and Call Service

using System; using System.ServiceModel; class Program { static void Main() { // Define the binding and endpoint address BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress endpoint = new EndpointAddress("http://localhost:8080/CalculatorService"); // Create ChannelFactory for ICalculator ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(binding, endpoint); // Create channel (proxy) ICalculator channel = factory.CreateChannel(); // Call service method int result = channel.Add(5, 7); Console.WriteLine("Result: " + result); // Close channel and factory ((IClientChannel)channel).Close(); factory.Close(); } }

🔹 How It Works

  • You provide the binding and endpoint to the ChannelFactory.

  • CreateChannel() returns a proxy implementing your service contract.

  • You invoke operations as if calling a local method.

  • You manage the lifetime of the channel and factory (close/dispose).


🧠 Interview One-Liner

ChannelFactory in C# is used in WCF to create a dynamic client proxy for a service endpoint without relying on generated client classes.


What is difference between Singleton and Static class in C#? Example.

Singleton:- allows a class for which there is just one, persistent instance across the lifetime of an application. 

Static class :-allows only static methods and and you cannot pass static class as parameter. 

Singleton :-can implement interfaces, inherit from other classes and allow inheritance.

A- Singleton objects are stored in Heap, but static objects are stored in stack

B-We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object.

C-Singleton classes follow the OOP (object oriented principles), static classes do not.

D-We can implement an interface with a Singleton class, but a class's static 
methods (Example:- a C# static class) cannot.


Important  :- Static Classes have only one object life, Hence we cannot create multiple objects of 
static classes but normal classes can be instantiated for creating many objects of the same class.

We use Static classes in scenarios in like creating a utilities class, implementing a singleton pattern.








What is use of Anonymous methods in C#? Example.

Anonymous methods provide a technique to pass a code block as a delegate parameter.

Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method.

It is inferred from the return statement inside the method body.

Example 

public delegate void Print(int value);

static void Main(string[] args)
{
    Print print = delegate(int val) 
    {
        Console.WriteLine("Inside Anonymous method. Value: {0}", val);
    };

    print(100);
}