1 Language Preliminaries

NET Centric Computing · Unit 1 · 8 hrs

Language Preliminaries

Exam-focused notes for Language Preliminaries (NET Centric Computing, CSC378): what the TU syllabus asks and how it has actually been tested, with 13 solved past questions from this unit.

Language Preliminaries in short

This unit lays down the C# language vocabulary that the rest of the course assumes: the .NET Framework and its runtime, the everyday language constructs, the object oriented features (constructors, properties, inheritance, interfaces, delegates), and the functional and safety features (generics, LINQ, exceptions, attributes, async/await) that ASP.NET Core code is written in.

Language Preliminaries: notes

Introduction to .Net framework

The .NET Framework is a software framework designed and developed by Microsoft. Its first version, 1.0, was released in 2002, and it is used to build Windows form based applications, web based applications, and web services. The framework supports more than 60 programming languages, of which 11 are designed and maintained by Microsoft, including C#, VB.NET, C++/CLI and JScript.NET.

The framework has three main layers:

  • The Common Language Runtime (CLR) is the runtime environment for every .NET program. It behaves like a virtual machine that executes all .NET languages, and every .NET language must obey the rules the CLR imposes for object creation, data types, and error and exception handling.
  • The Framework Class Library (FCL) is a collection of reusable, object oriented class libraries and methods that integrate with the CLR, comparable to header files in C/C++ or packages in Java.
  • The applications layer sits on top of these two: Windows Forms for desktop applications, ASP.NET for browser based web applications, and ADO.NET for applications that talk to a database such as SQL Server or Oracle.

Compilation and execution of .Net applications

Code written in any .NET compliant language is compiled into MSIL (Microsoft Intermediate Language), packaged inside an assembly, following the rules of the Common Type System (CTS) and Common Language Specification (CLS). MSIL is the language the CLR understands. At execution time, the CLR's just in time (JIT) compiler translates this IL into native binary code for the machine it is running on, and the resulting assemblies are loaded into memory.

Compilation can target a Debug or a Release configuration. A Debug build produces an unoptimized assembly with debug symbols attached, which makes step through debugging possible. A Release build performs full optimization and strips out the debug symbols, producing smaller, faster code intended for deployment.

Basic Languages constructs

C# supports the usual value types (int, short, long, char, bool, float, decimal, double), string, and object. A variable is declared with type name = value;, for example int x = 5;.

Conditional execution is expressed with if, if...else, if...else if, and switch. Repetition is expressed with for, while, do...while, and foreach, the last of which walks every element of a collection:

using System;

namespace ForEachDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[] { "Alpha", "Beta", "Gamma" };
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
        }
    }
}

Constructor

A constructor is a special method that is invoked automatically whenever an instance of a class is created. It shares the class's name, never declares a return type (not even void), and is used to give a new object its initial state. A class may declare any number of constructors as long as their parameter lists differ; a constructor with no parameters is a default constructor, and one with at least one parameter is a parameterized constructor.

public class Student
{
    public string Name;
    public int Id;

    public Student(string name, int id)
    {
        this.Name = name;
        this.Id = id;
    }

    public static void Main()
    {
        Student obj = new Student("Sagar", 1);
        Console.WriteLine("Name=" + obj.Name + " Id=" + obj.Id);
    }
}

Properties

Properties expose an object's data through get and set accessors, giving more control over how a value is read or written than a plain public field would. A property can wrap a private backing field, or be written as an auto-property when no extra logic is needed.

public class SampleClass
{
    private int sample;

    public int SampleProperty
    {
        get { return sample; }
        set { sample = value; }
    }

    public int AutoProperty { get; set; }
}

Arrays and String

An array is declared as type[] name; and can be initialized with new type[size], an explicit size and value list, or an implicit list: int[] arr = {1, 2, 3, 4, 5};. A multi-dimensional array adds a comma inside the brackets, for example int[,] arr = new int[3, 2];. A jagged array is an array of arrays, declared with two sets of brackets, where each inner array can have its own length:

int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2, 3, 4, 5 };
jagged[1] = new int[] { 4, 10 };
jagged[2] = new int[] { 4, 5, 6, 7 };

Arrays of string follow the same rules, for example string[] names = new string[4];.

What this unit covers

  • Introduction to .Net framework
  • Compilation and execution of .Net applications
  • Basic Languages constructs
  • Constructor
  • Properties
  • Arrays and String
  • Indexers
  • Inheritance
  • use of "base" keyword
  • Method hiding and overriding
  • applying polymorphism in code extensibility
  • structs and enums
  • abstract class sealed class
  • interface
  • Delegate and Events
  • Partial class
  • Collections
  • Generics
  • File IO
  • LINQ (Language Integrated Query) Fundamentals: Lambda Expressions
  • Try statements and Exceptions
  • Attributes: Attribute Classes, Named and Positional Attribute Parameters, Attribute Targets, Specifying Multiple Attributes
  • Asynchronous Programming: Principle of Asynchrony, Async/Await patterns in C#

Attributes

2081 · 10 marks

Distinguish between collection and generics. What are named and positional attribute parameters? Write a program to create your own exception when the user gives subject name than 'C#'.[10]

--- Basis Collection Generics --------- Namespace System.Collections System.Collections.Generic Type Safety Not type-safe; stores objects of any type Type-safe; stores objects of a specific type Data Type Works with object type (non-generic) Works with a specific declared type <T Boxing/Unboxing ...

Open this answer on its own page →

2078 · 5 marks

What is named and positional attribute parameters? Describe the .Net architecture design and principles. [5]

Show solved answer

Named and Positional Attribute Parameters & .NET Architecture Design and Principles


Part 1: Named and Positional Attribute Parameters

From the notes, the syntax for an attribute is:

[attribute(positional_parameters, name_parameter=value, ...)]
element

Positional Parameters

  • Positional parameters are the mandatory parameters of an attribute.
  • They must be passed in a fixed order as defined in the attribute constructor.
  • They correspond directly to the constructor arguments of the attribute class.

Example:

[Obsolete("This method is deprecated")]
public void OldMethod() { }

Here, "This method is deprecated" is a positional parameter passed in order.

Named Parameters

  • Named parameters are optional parameters of an attribute.
  • They are specified using a name=value syntax and can be provided in any order.
  • They correspond to properties or fields of the attribute class.

Example:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]

Here:

  • AttributeTargets.Class is the positional parameter (mandatory, in order).
  • AllowMultiple = true and Inherited = false are named parameters (optional, any order).

Part 2: .NET Architecture Design and Principles

.NET Architecture Overview

The layered architecture of .NET (as described in the notes) is as follows:

+------------------------------------------+
|  VB.NET | C# | JScript.NET | More Languages |
+------------------------------------------+
|   Common Language Specification (CLS)    |
+------------------------------------------+
|      Common Type System (CTS)            |
+------------------------------------------+
|   .NET Framework Class Library (FCL)     |
+------------------------------------------+
| ASP.NET | Windows Forms | Console | ADO.NET |
| Web Forms | XML Web Services | .NET Remoting |
+------------------------------------------+
|  Common Language Runtime (CLR)           |
|  [JIT Compilers, Security Manager, etc.] |
+------------------------------------------+
|  Common Language Infrastructure (CLI)    |
+------------------------------------------+
|          Operating System                |
+------------------------------------------+

Key Components Explained

ComponentDescription
CLR (Common Language Runtime)The heart of .NET Framework. Resides above the OS and handles all .NET applications. Manages garbage collection, Code Access Security (CAS), and memory management.
CLI (Common Language Infrastructure)Provides a language-independent platform for app development. Handles exception handling, garbage collection, and security.
CTS (Common Type System)Specifies a standard that defines what types of data and values can be defined and managed in memory at runtime.
CLS (Common Language Specification)A subset of CTS that defines rules and regulations that every .NET language must follow to ensure interoperability.
FCL (Framework Class Library)Provides system functionality including classes, interfaces, and data types to build desktop, web, and mobile applications.

Design Principles of .NET

  1. Clean Architecture: Applications following the Dependency Inversion Principle and Domain-Driven Design (DDD) are known as clean architecture. It places business logic and application model at the center.

  2. MVC Pattern: Separates the application into three components:

    • Model: Represents the shape/structure of data.
    • View: User interface that displays model data.
    • Controller: Handles user requests and manages the flow.
  3. N-Tier Architecture: ASP.NET Core automatically creates a pre-defined N-tier architecture for developers, saving time and effort, and easing tier deployment.

  4. Separation of Concerns: Each layer/component handles a specific responsibility, making the application maintainable and testable.

  5. Language Interoperability: Through CLS and CTS, .NET supports multiple languages (C#, VB.NET, JScript.NET) that can work together seamlessly.


Summary: .NET architecture is a layered, language-independent framework where CLR acts as the execution engine, CTS/CLS ensure type safety and interoperability, and FCL provides reusable libraries. Its design principles promote clean, maintainable, and scalable application development.

Open this answer on its own page →

Inheritance

2081 · 5 marks

Create a class named EMPLOYEE as super class and ENGINEER and DOCTOR as sub class. Make your own assumptions as properties and methods. [5]

This question demonstrates inheritance in C, where a base (super) class EMPLOYEE is created, and derived (sub) classes ENGINEER and DOCTOR inherit its properties and methods. The derived classes extend the base class with their own specific properties and methods. --- --- --- --- Feature Descript...

Open this answer on its own page →

applying polymorphism in code extensibility

2081 · 10 marks

Write short notes on: a. Polymorphism b. Hidden Field [5+5]

Show solved answer

Short Notes


a. Polymorphism (5 Marks)

Definition

The word polymorphism means "having many forms." It is the ability of a function, method, or object to behave differently in different contexts. In C#, polymorphism can be static (compile-time) or dynamic (run-time).


1. Static Polymorphism (Compile-Time Polymorphism)

The mechanism of linking a function with an object during compile time is called static binding. C# implements static polymorphism through function overloading.

In function overloading, multiple methods share the same name but differ in the number or type of parameters.

Example:

using System;
namespace PolymorphismApplication {
    class Printdata {
        void print(int g) {
            Console.WriteLine(g);
        }
        void print(double f) {
            Console.WriteLine(f);
        }
        void print(string s) {
            Console.WriteLine(s);
        }
    }
}

Here, the method print() is overloaded to handle int, double, and string data types. The compiler decides which version to call at compile time.


2. Dynamic Polymorphism (Run-Time Polymorphism)

C# allows the creation of abstract classes that provide partial class implementation. The implementation is completed when a derived class inherits from the abstract class and overrides its methods. The correct method is resolved at run time.

Key Points:

  • Uses abstract keyword for the base class and methods.
  • Derived classes use override keyword to provide specific implementations.
  • Enables method overriding.

Example:

abstract class Shape {
    public abstract void Draw();
}
class Circle : Shape {
    public override void Draw() {
        Console.WriteLine("Drawing Circle");
    }
}
class Rectangle : Shape {
    public override void Draw() {
        Console.WriteLine("Drawing Rectangle");
    }
}

Importance of Polymorphism

  • Promotes code extensibility and reusability.
  • Allows a single interface to represent different underlying forms (data types or classes).
  • Makes programs easier to maintain and scale.

b. Hidden Field (5 Marks)

Definition

A hidden field is an HTML form element that allows data to be stored on the client side without being displayed on the page. When the user performs an action (such as form submission), the hidden field value is passed back to the server side along with the form data.


Purpose

Sometimes we require certain data (such as a user ID or session-related value) to be available across requests without showing it to the user. Hidden fields serve this purpose by embedding the data in the HTML form invisibly.


How Hidden Fields Work in ASP.NET Core MVC

Step 1: GET Method - Set the hidden field value

The GET version of the action method creates an object and passes it to the view:

[HttpGet]
public IActionResult SetHiddenFieldValue() {
    User newUser = new User() {
        Id = 101,
        Name = "John",
        Age = 31
    };
    return View(newUser);
}

Step 2: View - Render the hidden field

In the view, the Id field is rendered as a hidden input so it is not visible to the user but is included in the form:

@model User
<form method="post">
    <input type="hidden" name="Id" value="@Model.Id" />
    <input type="text" name="Name" value="@Model.Name" />
    <button type="submit">Submit</button>
</form>

Step 3: POST Method - Read the hidden field value

The POST version reads the hidden field value from IFormCollection:

[HttpPost]
public IActionResult SetHiddenFieldValue(IFormCollection keyValues) {
    var id = keyValues["Id"];   // Retrieves the hidden field value
    return View();
}

Key Points

AspectDetail
VisibilityNot visible to the user on the page
TransmissionSent to the server on form submission
Use CaseStoring IDs, tokens, or state data across requests
SecurityShould not be used for sensitive data as it can be viewed in page source

Summary

Hidden fields are a simple and effective way to persist data between HTTP requests in a stateless web environment without exposing it in the UI. In ASP.NET Core MVC, they are commonly used with IFormCollection or model binding to retrieve the stored values on the server side.

Open this answer on its own page →

Partial class

2080 · 10 marks

What are the needs for partial class and sealed class? How do you relate delegate with events? State the steps to deploy .NET core application.[10]

--- A partial class allows a single class definition to be split across multiple files. All parts are combined into one class at compile time using the partial keyword. Syntax: Needs / Reasons to use Partial Class: Need Explanation ------------------- Large class management Splits a large class i...

Open this answer on its own page →

Generics

2080 · 5 marks

Differentiate between generic and non-generic collections. Write a simple program to create generic class with generic constructor, generic member variable, generic property and generic method. [5]

Feature Generic Collection Non-Generic Collection --------- Namespace System.Collections.Generic System.Collections Type Safety Type-safe at compile time Not type-safe (stores object) Boxing/Unboxing No boxing/unboxing needed Requires boxing/unboxing for value types Performance Better performance...

Open this answer on its own page →

LINQ

2080 · 15 marks

Write short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]

Show solved answer

Short Notes (Any Two)


a. Lambda Expression

Definition

A lambda expression is an anonymous function that can be used to create delegates or expression tree types. Lambda expressions are a concise way to write inline functions and are heavily used in LINQ (Language Integrated Query) in C#.

Syntax

(parameters) => expression

or for a block body:

(parameters) => { statements; }

Key Characteristics

  • The => operator is called the lambda operator and is read as "goes to".
  • Lambda expressions can have zero, one, or multiple parameters.
  • They can be used wherever a delegate type is expected.
  • They are a core part of LINQ support in C#, alongside query expressions, object initializers, and collections.

Example

// Simple lambda expression
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25

// Lambda with LINQ
int[] scores = new int[] { 97, 92, 83, 60 };
var highScores = scores.Where(score => score > 80);
foreach (int s in highScores)
    Console.WriteLine(s);
// Output: 97 92 83

Why Use Lambda Expressions?

  • Makes code shorter and more readable.
  • Eliminates the need to define a separate named method for simple operations.
  • Integrates seamlessly with LINQ to query collections, databases, XML, and more.
  • Supports functional programming style in C#.

b. Cross Site Request Forgery (CSRF)

Definition

Cross-Site Request Forgery (CSRF) is a web security attack where an attacker tricks an authenticated user into unknowingly submitting a malicious request to a web application on which the user is currently authenticated.

How CSRF Works

  1. The user logs into a trusted website (e.g., a banking site) and a session cookie is stored in the browser.
  2. Without logging out, the user visits a malicious website.
  3. The malicious site contains a hidden request (e.g., a form or image tag) that sends a request to the trusted website.
  4. Since the browser automatically includes the session cookie, the trusted website processes the request as if it came from the legitimate user.

Example Attack Scenario

<!-- Malicious page sends a hidden request to the bank -->
<img src="http://bank.com/transfer?amount=10000&to=attacker" />

The browser automatically sends the authenticated cookie along with this request.

Difference from XSS

FeatureXSSCSRF
Attack targetOther users via injected scriptsAuthenticated user's session
MechanismInjects malicious scripts into pagesForges requests using existing session
Trust exploitedUser trusts the websiteWebsite trusts the user's browser

Prevention Techniques

  • Anti-CSRF Tokens: Include a unique, secret token in every form that the server validates.
  • SameSite Cookie Attribute: Restricts cookies from being sent with cross-site requests.
  • Re-authentication: Require password confirmation for sensitive actions.
  • Checking Referer/Origin headers: Validate that requests originate from the expected domain.

c. Single Page Application (SPA)

Definition

A Single Page Application (SPA) is a web application that loads a single HTML page and dynamically updates the content as the user interacts with the app, without requiring a full page reload from the server.

How SPA Works

  • On the first request, the server sends a single HTML page along with all necessary JavaScript and CSS.
  • Subsequent interactions (navigation, data loading) are handled via AJAX calls to the server, which returns only data (typically JSON), not full HTML pages.
  • The browser's JavaScript framework (e.g., Angular, React, Vue.js) updates the DOM dynamically.

Architecture Diagram

User Action --> JavaScript (Client Side) --> AJAX Request --> Server API
                        |                                         |
                   DOM Updated <-------------- JSON Response -----+

Key Characteristics

  • Only one full page load occurs (at the start).
  • Uses client-side routing to simulate navigation between pages.
  • Heavy use of JavaScript frameworks like Angular, React, or Vue.js.
  • Communicates with the backend via REST APIs or GraphQL.

Advantages

AdvantageDescription
Fast and responsiveNo full page reloads; only data is exchanged
Better user experienceFeels like a desktop application
Reduced server loadServer only sends data, not full HTML
Separation of concernsFrontend and backend are clearly separated

Disadvantages

  • SEO challenges: Search engines may struggle to index dynamically loaded content.
  • Initial load time can be slow as all JavaScript is loaded upfront.
  • Browser history management requires extra handling.
  • Security: Requires careful handling of authentication tokens (e.g., JWT).

Example Technologies

  • Frameworks: Angular, React, Vue.js
  • Communication: AJAX, Fetch API, Axios
  • Routing: React Router, Angular Router
Open this answer on its own page →

2079 · 15 marks

Write short notes on: (any two) 1. Lambda Expression 2. Containerization using Docker 3. Delegates and Events [5+5+5]

--- A lambda expression is a convenient way of defining an anonymous (unnamed) function that can be passed around as a variable or as a parameter to a method call. Lambda expressions are closely associated with LINQ (Language Integrated Query), as many LINQ methods take a function (called a deleg...

Open this answer on its own page →

2078 · 15 marks

Write short notes on (any two): a. LINQ b. Open Redirected Attack c. Query String [5+5+5]

--- Definition: LINQ (Language Integrated Query) is the name for a set of technologies based on the integration of query capabilities directly into the C language. With LINQ, a query is a first-class language construct, just like classes, methods, and events. Key Features: - LINQ is simpler, well...

Open this answer on its own page →

Collections

2079 · 10 marks

What is the purpose of web form? Write a program to demonstrate the concept of collection and generics.[10]

A Web Form in ASP.NET is a page that allows users to interact with a web application by entering and submitting data through HTML form elements such as text boxes, dropdowns, checkboxes, and buttons. Purpose Description ------ Data Collection Collects user input such as name, email, roll number, ...

Open this answer on its own page →

structs and enums

2078 · 10 marks

Differentiate between struct and enum. Why do we need to handle the exception? Illustrate with an example with your own customized exception.[10]

--- As per the course notes, the key differences are: Feature Struct Enum --------- Keyword struct keyword is used to declare a structure enum keyword is used to declare an enumeration Contents Can contain both data variables and methods Can only contain data types (named integer constants) Acces...

Open this answer on its own page →

Try statements and Exceptions

2076 · 5 marks

Explain error handling in ASP.[5]

Error handling (Exception Handling) in C is a mechanism to detect and handle run-time errors in code. The CLR (Common Language Runtime) supports error and exception handling as one of its core responsibilities. C provides three keywords to implement exception handling: - try - catch - finally ---...

Open this answer on its own page →

File IO

2076 · 5 marks

Explain about file access with ASP with example.[5]

File access in ASP.NET allows web applications to read from and write to files stored on the server. ASP.NET provides built-in classes through the System.IO namespace to handle file input/output operations. The two main streams used are: - Input Stream: Used for reading data from a file - Output ...

Open this answer on its own page →