0% found this document useful (0 votes)
27 views

New Features

The document discusses various C# features including references, copy constructors, object initializers, nullable types, the ?? operator, covariance and contravariance. It explains that references in C# are pointers to objects created in the heap. Copy constructors allow cloning objects by copying property values. Object initializers automatically implement get/set accessors for properties. Nullable types allow value types to be assigned null using ? syntax. The ?? operator returns the left operand if not null, otherwise the right. Covariance and contravariance relate to delegate parameter and return types allowing more or less derived types.

Uploaded by

Tinu Bhatnagar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

New Features

The document discusses various C# features including references, copy constructors, object initializers, nullable types, the ?? operator, covariance and contravariance. It explains that references in C# are pointers to objects created in the heap. Copy constructors allow cloning objects by copying property values. Object initializers automatically implement get/set accessors for properties. Nullable types allow value types to be assigned null using ? syntax. The ?? operator returns the left operand if not null, otherwise the right. Covariance and contravariance relate to delegate parameter and return types allowing more or less derived types.

Uploaded by

Tinu Bhatnagar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

10/9/2016

References
• The types created for classes are called references.
• Unlike other basic types (like int, float etc. that are created in
the stack), references are created in the heap.
C# New Features • They are implicit pointers to the object created.
• The space for the object allocation is not done until runtime.
Point p1= new Point(10,20)
Miscellaneous Features
Point p2= new Point(20,30);
x=10
 Objects created in the heap are y=20
p1
automatically garbage collected. So no
explicit freeing of memory is needed. x=20
p2 y=30
 p1 and p2 are in stack of method in
which they are created.
[email protected] [email protected]

Copy constructor Deep copy


• If we need to clone an object, one way to do this is to • If a class has a reference as a member, then we must
write a copy constructor. make sure that the copy constructor creates a new
public class Point{
public int x ; object for the reference, instead of a shallow copy.
public int y ; public class Circle{
public Point(Point p) {
x = p.x; Point p;
y=p.y; double radius;
}
public Circle(Circle c){

} radius=c.radius;
p=c.p; // shallow copy
• Now we can create a Point object from another one
p= new Point(c.p.x,c.p.y); //deep copy
by calling copy constructor
}
Point p= new Point(1,2);
Point p1= new Point(p); …
}
[email protected] [email protected]

Object initializers Auto Implemented Properties


Access-specifier type name { get; set; } • It makes it possible to initialize an object’s properties,
• Object initializers are automatically implemented properties where both get even if the class doesn’t supply a constructor that
and set accessors are defined automatically. allows you to supply the specific values.
• We cannot have one accessor automatically implemented and the other using System;
explicitly implemented. public class Customer
{
• Also, in this case, the compiler creates a private, anonymous backing field public string Name { get; set; }
that can only be accessed through the property's get and set accessors. public string Product { get; set; }
}
using System;
public class AutoImplementedCustomerManager
public class Point{ {
public int X { get; set; } static void Main()
public int Y { get; set; } {
public static void Main() Customer s = new Customer() { Name = "Abc", Product = "TV" };
{ Console.WriteLine(s.Name);
Point p = new Point { X = 10, Y = 20 }; Console.WriteLine(s.Product);
Console.WriteLine("({0}, {1})",p.X,p.Y); }
}} }

[email protected] [email protected]

1
10/9/2016

C# Nullable Types The ?? Operator


• We know that the default value for reference type is null. • ?? operator allows us to assign a default value to a nullable
• Reference values can also be explicitly assigned to null value types or reference types.
• It returns the left-hand operand if the operand is not null. If it
string s=null;
is null, the right hand operand is returned.
• Value types cannot be set to null
• This is also called null-coalescing operator.
int i=null;// error
int? i = null;
• But with a slight change in syntax we can make it work!
Console.WriteLine(i ?? -1); //prints -1
int? i=null;
string s = null;
• This syntax allows the assigning of null value to the value Console.WriteLine(s ?? "not assigned");
type.
// prints not assigned
• This is useful when we want to represent no value.
• Note that Int32 i=null; is also an error
• For instance, no value for int cannot be 0 because 0 may
be considered as valid value.
[email protected] [email protected]

Covariance and Contra variance Example


• Covariance permits a method to have a more using System;
namespace DelegateDemo
derived return type than what is defined in {
public class Employee { … }
the delegate. public class Manager : Employee {
delegate object Display(Manager e);
… }

class Program
• Contra variance permits a method with { Covariance Contravariance
static string consoledisplay(Employee m)
parameter types that are less derived than in {
m.print();
the delegate type. return "success";
}
• In the following example, We will use the static void Main()
{
Employee (Base) and Manager (Derive) Manager e = new Manager(1, "Mohan", "Type 2");
Display d = new Display(consoledisplay);
class. Manager inherits from Employee and it }
Console.WriteLine(d(e));

overrides Employees print() method. }


}

[email protected] [email protected]

Extension Methods Using Extension Method


• Extension Methods allow developers to extend • The code in the previous slide shows the
existing types from within a separate class, making it extension method named Echo declared in
possible to add new functionality to existing classes the StringExtension class.
public static class StringExtension
{
public static void Echo(this string s)
• Now you can invoke the Echo method like an
{
Console.WriteLine("Supplied string : " + s);
instance method with a string.
}
public static string ToMixedCase(this string s) • The string is passed with the first parameter
{
StringBuilder sb = new StringBuilder(s.Length); of the method.
for (int i = 0; i < s.Length; i++)
{
sb.Append(i % 2 == 0 ? s[i].ToString().ToLower() : static void Main()
s[i].ToString().ToUpper()); {
} string s = "Hello world";
return sb.ToString(); s.Echo();
}
} }

[email protected] [email protected]

2
10/9/2016

Key Characteristics Collection Initializers


• Based on the code, here are the key characteristics of • Collection initializers let you specify one or
extension methods. more element initializers when you initialize a
1. Extension methods have the keyword this before the first collection class that implements IEnumerable
parameter
2. When extension methods are consumed, the argument that
or a class with an Add extension method.
was declared with the keyword this is not passed. In the • The element initializers can be a simple
code, note the invocation of Echo() method without any value, an expression or an object initializer.
arguments
3. Extension methods can be defined only in a static class
By using a collection initializer you do not
4. Extension methods can be called only on instances. Trying have to specify multiple calls to the Add
to call them on a class will result in compilation errors. The method of the class in your source code; the
classes instances on which they are called are determined compiler adds the calls.
by the first argument in the declaration, the one having the
keyword this.
[email protected] [email protected]

Example Example Contd.


using System; List<Cat> moreCats = new List<Cat>
using System.Collections.Generic; {
class ObjInitializers new Cat(){ Name = "Furrytail", Age=5 },
{ new Cat(){ Name = "Peaches", Age=4 },
class Cat null
{ };
// Auto-implemented properties.
public int Age { get; set; } // Display results.
public string Name { get; set; } Console.WriteLine(cat.Name);
}
static void Main() foreach (Cat c in cats)
{ Console.WriteLine(c.Name);
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
List<Cat> cats = new List<Cat> foreach (Cat c in moreCats)
{ if (c != null)
new Cat(){ Name = "Sylvester", Age=8 }, Console.WriteLine(c.Name);
new Cat(){ Name = "Whiskers", Age=2 }, else
new Cat(){ Name = "Sasha", Age=14 } Console.WriteLine("List element has null value.");
}; }
}

[email protected] [email protected]

Anonymous Types Example Contd.


• Anonymous Types allow to generate new types at static void Main()
{
compile time for which developers don’t know, and Cat cat = new Cat { Age = 10, Name = "Fluffy" };
don’t need to know the names. var objAnonymous = new { cat.Name, cat.Age };
Console.WriteLine(objAnonymous.Name + " " +
• The type name is generated by the compiler and is not objAnonymous.Age);
available at the source code level. The type of each var objAnonymous1 = new { Prop1 = 10, Prop2 = "Demo" };
property is inferred by the compiler. Console.WriteLine(objAnonymous1.Prop1 + " " +
objAnonymous1.Prop2);
using System;
class ObjInitializers var v = new { Amount = 108, Message = "Hello" };
{ Console.WriteLine(v.Amount + " " + v.Message);
class Cat
{ }
// Auto-implemented properties. }
public int Age { get; set; }
public string Name { get; set; }
}

[email protected] [email protected]

3
10/9/2016

Lambda expression Lambda Expression Example


• A lambda expression is an anonymous function that can be • Following is an example of Lambda
used to create delegates or expression tree types.
Expression.
• The conditional expression that the LINQ uses with the where
clause is actually passed as an argument to the Where using System;
class X
method: {
Where(flower.Petals => flower.Petals == 5) delegate int cube(int i);
static void Main(string[] args)
• The above expression is called Lambda expression. {
cube myDelegate = x => x * x * x;
• => is the lambda operator, which is read as "goes to". int j = myDelegate(5);
• While many LINQ can be written without the knowledge of Console.WriteLine(j);
}
Lambda expression, some queries can only be expressed in }
method syntax and require us to use lambda expressions.
• It is very easy to use aggregate functions with lambda
expression.
[email protected] [email protected]

Why do we need lambda expressions? Simple Example


• Convenience. It's a shorthand that allows you to write • How do we define a lambda expression?
a method in the same place you are going to use it. Parameters => Executed code
• Especially useful in places where a method is being n => n % 2 == 1;
used only once, and the method definition is short. It
saves you the effort of declaring and writing a separate
• You can read n => n % 2 == 1 like:
method to the containing class. "input parameter named n goes to anonymous
• Reduced typing. No need to specify the name of the function which returns true if the input is odd".
function, its return type, and its access modifier. • Now to execute the lambda
• When reading the code you don't need to look List<int> numbers = new List<int> { 11, 37, 52 };
List<int> oddNumbers = numbers.Where(n => n % 2 == 1).ToList();
elsewhere for the method's definition. foreach (var item in oddNumbers)
• Lambda expressions should be short. A complex {
Console.WriteLine(item);
definition makes the calling code difficult to read. }

[email protected] [email protected]

Named Arguments Optional Parameters


• Named Arguments allows you to change the orders of • The definition of a method, constructor, indexer, or delegate
parameters. You don’t required to remember the order can specify that its parameters are required or that they are
of parameters in the parameter lists of called methods. optional.
using System; • Any call must provide arguments for all required parameters,
class Program but can omit arguments for optional parameters.
{
static void Main(string[] args) { • Each optional parameter has a default value as part of its
double l, b;
Console.Write("Enter length of Rectangle:"); definition. If no argument is sent for that parameter, the
l = double.Parse(Console.ReadLine()); default value is used, which must be one of the following
Console.Write("Enter breadth of Rectangle:");
b = double.Parse(Console.ReadLine()); types of expressions:
Area(l, b); Area(bb: b, ll: l); Area(l, bb: b);
}
• a constant expression;
public static void Area(double ll, double bb) • an expression of the form new ValType(), where ValType is a value
{
Console.WriteLine("\nArea of Rectangle:" + ll * bb);
type, such as an enum or a struct;
} • an expression of the form default(ValType), where ValType is a
}
value type.
[email protected] [email protected]

4
10/9/2016

Example Dynamic
using System;
class Program • The dynamic type enables the operations in which it
{
static void Main() occurs to bypass compile-time type checking. Instead,
{
//Omit the optional parameters. these operations are resolved at run time.
Fun();
//Omit second optional parameter. • The dynamic type simplifies access to COM APIs such
Fun(4);
//You can't omit the first but keep the second.
as the Office Automation APIs, and also to dynamic
//Fun("Dot"); APIs such as IronPython libraries, and to the HTML
//Classic calling syntax.
Fun(4, "Dotnet"); Document Object Model (DOM).
//Specify one named parameter.
Fun(name: "Ram"); • Type dynamic behaves like type object in most
//Specify both named parameters.
Fun(value: 5, name: "Hari"); circumstances. However, operations that contain
}
static void Fun(int value = 101, string name = "C#") expressions of type dynamic are not resolved or type
{
Console.WriteLine("value = {0}, name = {1}", value, name);
checked by the compiler.
}
}

[email protected] [email protected]

More About Dynamic Example - Dynamic


• The compiler packages together information about the • The following example contrasts a variable of type
operation, and that information is later used to dynamic to a variable of type object.
evaluate the operation at run time. • To verify the type of each variable at compile time,
• As part of the process, variables of type dynamic are place the mouse pointer over dyn or obj in the
compiled into variables of type object. Therefore, type WriteLine statements. IntelliSense shows dynamic for
dynamic exists only at compile time, not at run time. dyn and object for obj.
• The dynamic is a new static type that acts like a using System;
class Program
placeholder for a type not known until runtime. Once {
static void Main(string[] args)
the dynamic object is declared, it is possible to call {
dynamic dyn = 1;
operations, get and set properties on it, even pass the object obj = 1;
Console.WriteLine(dyn.GetType());
dynamic instance pretty much as if it were any normal Console.WriteLine(obj.GetType());
}
type. }

[email protected] [email protected]

Another Example Code Block


using System;
• The dynamic keyword is used to replace class Program
{
other types such as int, bool or string. In this static dynamic _y;
static void Main()
example, we assign the value 1 to the {
// Use dynamic local.
dynamic variable a. This means "a" is of type dynamic a = 1;
Console.WriteLine(a);
System.Int32 at that point. // Dynamic now has a different type.
a = new string[0];
• Next, we assign it to a string array. The type Console.WriteLine(a);
// Assign to dynamic
// You can call anything on a dynamic

again changes. You can also use dynamic as // method result.


a = Test();
variable,
// ... but it may result in a

a return type (or formal parameter type). Console.WriteLine(a);


// Use dynamic field.
runtime error.
Console.WriteLine(_y.Error);

Finally, we use a dynamic static field, and _y = "carrot";


}
static dynamic Test()

call a nonexistent property on it. {


return 1;
}
}

[email protected] [email protected]

5
10/9/2016

Thanks

[email protected]

You might also like