Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Chapter 02 - C# Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 02 - C# Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

C#.

NET Programming
Objectives
◆ Explain about input/output in C#
◆ Create C# Console Application using Visual Studio.NET
◆ Describe more new features of C# :
▪ var and dynamic type
▪ ref, out and params
▪ Local Function and Static Local Function
▪ String Interpolation
▪ Null-Condition Operator
▪ Ref locals and Ref returns
▪ Discards and Pattern Matching
▪ Numeric literal syntax
▪ Tuples
11/02/2021 2
Introduction to C#
◆ C# is an object-oriented, component-oriented programming language
◆ C# provides language constructs to directly support these concepts, making
C# a natural language in which to create and use software components
◆ Several C# features help create robust and durable applications:
▪ Garbage collection automatically reclaims memory occupied by
unreachable unused objects
▪ Exception handling provides a structured and extensible approach to error
detection and recovery
▪ Lambda expressions support functional programming techniques.
Language Integrated Query (LINQ) syntax creates a common pattern for
working with data from any source. Language support for asynchronous
operations provides syntax for building distributed systems and so on
11/02/2021 3
Demo Create C# Console App using Visual
Studio.NET

11/02/2021 4
1. Open Visual Studio.NET , File | New | Project
1

11/02/2021 5
2. Fill out Project name: HelloWorldApp and Location then click Next

11/02/2021 6
3. Choose Target Framework: .NET 8.0 (Long Term Support) then click
Create

11/02/2021 7
4. Write code for Main method then press F5(run Debugging) or Ctrl+F5(run
without Debugging) to run application

11/02/2021 8
Structure of a C# program
Referencing
namespace
Namespace of
the current class
Entry point:
Main()

11/02/2021 9
Namespaces in C#
◆ Namespaces are used to organize the classes. It helps to control the scope
of methods and classes in larger .Net programming projects
◆ The biggest advantage of using namespace is that the class names which
are declared in one namespace will not clash with the same class names
declared in another namespace. It is also referred as named group of
classes having common features
◆ The members of a namespace can be namespaces, interfaces, structures,
and delegates.

11/02/2021 10
Namespaces in C#
◆ To define a namespace in C#, we will use the namespace keyword followed
by the name of the namespace and curly braces containing the body of the
namespace as follows:

11/02/2021 11
Namespaces in C#
◆ For console applications, .NET 8 the following directives are implicitly
included in the application:
◆ using System;
◆ using System.IO;
◆ using System.Collections.Generic;
◆ using System.Linq;
◆ using System.Net.Http;
◆ using System.Threading;
◆ using System.Threading.Tasks;

11/02/2021 12
Variations on the Main() Method
◆ By default, Visual Studio will generate a Main() method that has a void return
value and an array of string types as the single input parameter
◆ To construct application’s entry point using any of the following signatures:
static int Main(string[] args){ The Main() method can be asynchronous
// Must return a value before exiting! static Task Main()
return 0;
} static Task<int> Main()
// No return type, no parameters. static Task Main(string[])
static void Main(){ static Task<int> Main(string[])
}
// int return type, no parameters.
static int Main(){
// Must return a value before exiting!
return 0;
}
11/02/2021 13
Processing Command-Line Arguments
◆ Create C# Console App as the following and run it by dotnet CLI

11/02/2021 14
Value Types and Reference types
◆ Value types derive from System.ValueType, which derives from
System.Object. Types that derive from System.ValueType have special
behavior in the CLR(Common Language Runtime).
▪ There are two categories of value types: struct and enum
◆ Reference type: A type that is defined as a class, delegate, array, or
interface is a reference type.
▪ At run time, when declare a variable of a reference type, the variable
contains the value null until you explicitly create an object by using the new
operator, or assign it an object that has been created elsewhere by using
new
11/02/2021 15
Value Types and Reference types

11/02/2021 16
Boxing and Unboxing
◆ Boxing is the process of converting a value type to the type object or to any interface
type implemented by this value type. When the common language runtime (CLR)
boxes a value type, it wraps the value inside a System.Object instance and stores it
on the managed heap

11/02/2021 17
Boxing and Unboxing
◆ Unboxing is an explicit conversion from the type object to a value type or from an
interface type to a value type that implements the interface
◆ An unboxing operation consists of: Checking the object instance to make sure that it is a
boxed value of the given value type and Copying the value from the instance into the
value-type variable

If we change code line:


int j = (int)o to int j = (short)o
what happens?
11/02/2021 18
var keyword
◆ The var keyword can be used in place of specifying a specific data type (such
as int, bool, or string) and the compiler will automatically infer the underlying
data type based on the initial value used to initialize the local data point.

11/02/2021 19
var keyword
◆ The following restrictions apply to implicitly-typed variable declarations:
▪ var can only be used when a local variable is declared and initialized in the
same statement; the variable cannot be initialized to null, or to a method
group or an anonymous function
▪ var cannot be used on fields at class scope
▪ Variables declared by using var cannot be used in the initialization
expression
▪ Multiple implicitly-typed variables cannot be initialized in the same
statement

11/02/2021 20
dynamic type
◆ The dynamic type is a static type, the compiler does not check the type of
the dynamic type variable at compile time, instead of this, the compiler gets
the type at the run time
◆ In most of the cases, the dynamic type behaves like object types
◆ The dynamic type changes its type at the run time based on the value
present on the right-hand side
◆ To get the actual type of the dynamic variable at runtime by using GetType()
method
◆ Can pass a dynamic type parameter in the method so that the method can
accept any type of parameter at run time
11/02/2021 21
dynamic type

11/02/2021 22
String Interpolation
◆ The string interpolation feature is built on top of the composite formatting feature and
provides a more readable and convenient syntax to include formatted expression results
in a result string.
◆ To identify a string literal as an interpolated string, prepend it with the $ symbol
$ " <text> { <interpolation-expression> <optional-comma-field-width> <optional-colon-format> } <text> {... } "

11/02/2021 23
The Console Class
◆ The Console type defines a set of methods to capture input and output, all of which are
static, therefore, called by prefixing the name of the class Console to the method name

11/02/2021 24
Numeric Literal Syntax
◆When assigning large numbers to a numeric variable, there are more digits we can use
underscore (_) as a digit separator (for integer, long, decimal, double data, or hex types)
◆C# provides also a new literal for binary values allows for binary numbers to start with an
underscore

11/02/2021 25
Passing Parameters with ref, out and params
◆ In C#, arguments can be passed to parameters either by value or by
reference.
◆ Passing by reference enables function members, methods, properties,
indexers, operators, and constructors to change the value of the parameters
and have that change persist in the calling environment
◆ To pass a parameter by reference with the intent of changing the value, use
the ref, or out keyword
◆ The ref keyword makes the formal parameter an alias for the argument, which
must be a variable
◆ An argument that is passed to a ref parameter must be initialized before it is
passed
11/02/2021 26
Passing Parameters with ref, out and params
◆ Variables passed as out arguments do not have to be initialized before
being passed in a method call. However, the called method is required to
assign a value before the method returns

11/02/2021 27
Passing Parameters with ref, out and params
◆ The params keyword allows you to pass into a method a variable number of
identically typed parameters (or classes related by inheritance) as a single
logical parameter
◆ The arguments marked with the params keyword can be processed if the
caller sends in a strongly typed array or a comma-delimited list of items
◆ The parameter type must be a single-dimensional array
◆ No additional parameters are permitted after the params keyword in a
method declaration, and only one params keyword is permitted in a method
declaration

11/02/2021 28
Passing Parameters with ref, out and params

11/02/2021 29
Ref locals and Ref returns
◆ A reference return value(ref returns) allows a method to return a reference
to a variable, rather than a value, back to a caller. The caller can then
choose to treat the returned variable as if it were returned by value or by
reference. The caller can create a new variable that is itself a reference to
the returned value, called a ref local.
◆ A method that returns a reference return value must satisfy the following two
conditions:
▪ The method signature includes the ref keyword in front of the return type
▪ Each return statement in the method body includes the ref keyword in front of the
name of the returned instance

11/02/2021 30
Ref locals and Ref returns

11/02/2021 31
Local Function and Static Local Function
◆ The local function allows declaring a method inside the body of an already
defined method. Or in other words, we can say that a local function is a
private function of a function whose scope is limited to that function in which it
is created
◆ The type of local function is similar to the type of function in which it is defined.
We can only call the local function from their container members
◆ Local functions can be defined anywhere inside a method: the top, the bottom,
or middle
◆ Local function can access the local variables that are defined inside the
container method including method parameters
11/02/2021 32
Local Function and Static Local Function
◆ Local function allows to pass out/ref parameters, using generic and using
params keyword
◆ Cannot declare a local function in the expression-bodied member
◆ Not allowed to use any member access modifiers in the local function
definition, including private keyword because they are by default private
◆ Overloading is not allowed for local functions
◆ Using the static modifier to declare a local function as a static local
function, ensure the local function doesn’t reference any variables from
the enclosing scope
11/02/2021 33
Local Function and Static Local Function

11/02/2021 34
Local Function and Static Local Function

11/02/2021 35
Tuples
◆ The tuples feature provides concise syntax to group multiple data elements in a
lightweight data structure which gives us the easiest way to represent a data set that
has multiple values that may/may not be related to each other
◆ Each property in a tuple can be assigned a specific name (just like variables), greatly
enhancing the usability
◆ There are two important considerations for tuples: the fields are not validated and
cannot define our methods

11/02/2021 36
Tuples

11/02/2021 37
Discards

◆ C# allows discard the returned value which is not required. Underscore (_)
character is used for discarding the parameter

◆ Discards are equivalent to unassigned variables, they don't have a value.

◆ Discards can reduce memory allocations.

◆ Discards make the intent of our code clear. They enhance its readability
and maintainability.

11/02/2021 38
Discards
◆ Using discard with out parameter

11/02/2021 39
Discards
◆ Using discard with Tuples

11/02/2021 40
Pattern Matching
◆ Pattern matching allows the developer to match a value (or an object)
against some patterns to select a branch/block of the code through the use of
is patterns and case patterns
▪ The is pattern
• The is pattern allows we to check whether an input variable is of a certain type,
and then assign it to a new variable named count.
if (input is int count && count > 0)
• This pattern can also be used to check if an input variable is null:

if (input is null)
11/02/2021 41
Pattern Matching
▪ The case pattern
• The switch statement cases also support patterns. These patterns can include a type
check, plus additional conditions:

11/02/2021 42
Pattern Matching

11/02/2021 43
Null-Condition Operator
◆ Used to test for null before performing a member access (?.) or index (?[])
operation. These operators help we write less code to handle null checks
▪ If a evaluates to null, the result of a?.x or a?[x] is null.
▪ If a evaluates to non-null, the result of a?.x or a?[x] is the same as the result of a.x or
a[x], respectively.

11/02/2021 44
Nullable value types
◆ A nullable value type T? represents all values of its underlying value type T
and an additional null value

11/02/2021 45
Nullable reference types
◆ Nullable reference types follow many of the same rules as nullable value
types. Nullable reference types can be null, but still must be assigned
something before first use
◆ Nullable reference types use the same symbol (?) to indicate that they are
nullable

11/02/2021 46
Primary Constructors for Classes and Structs
◆ Define constructors directly within the class or struct declaration for concise
syntax.

◆ Usage:
Person person = new("John", "Doe");

11/02/2021 47
Alias Any Type
◆ Create aliases for any type, including unnamed types like tuples, for
improved readability and conciseness.

11/02/2021 48
Summary
◆ Explain about input/output in C#
◆ Demo create C# Console Application using Visual Studio.NET
◆ Describe more new features of C# :
▪ var and dynamic type
▪ ref, out and params
▪ Local Function and Static Local Function
▪ String Interpolation and Namespaces
▪ Null-Condition Operator and Nullable reference types
▪ Ref locals and Ref returns
▪ Discards and Pattern Matching
▪ Numeric literal syntax
▪ Tuples
▪ Primary Constructors for Classes and Structs
11/02/2021 49

You might also like