C Sharp 2.0

The computer programming language, C#, introduces several new features in version 2.0 (corresponding to the 3rd edition of the ECMA-334 standard and the .NET Framework 2.0). These include:

C# 2.0 Features

Partial class

Partial classes allow implementation of a class to be spread between several files, with each file containing one or more class members. It is useful primarily when parts of a class are generated automatically. For example, the feature is heavily used by code-generating user interface designers in Visual Studio.

file1.cs:

public partial class MyClass
{
    public void MyMethod1()
    {
        // Manually written code
    }
}

file2.cs:

public partial class MyClass
{
    public void MyMethod2()
    {
        // Automatically generated code
    }
}

Generics

Generics, or parameterized types, or parametric polymorphism is a .NET 2.0 feature supported by C# and Visual Basic. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.[1]

Static classes

Static classes are classes that cannot be instantiated or inherited from, and that only allow static members. Their purpose is similar to that of modules in many procedural languages.

Generator functionality

The .NET 2.0 Framework allowed C# to introduce an iterator that provides generator functionality, using a yield return construct similar to yield in Python.[2] With a yield return, the function automatically keeps its state during the iteration.

// Method that takes an iterable input (possibly an array)
// and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
    foreach (int i in numbers)
    {
        if (i % 2 == 0) 
            yield return i;
    }
}

There is also a yield break statement, in which control is unconditionally returned to the caller of the iterator. There is an implicit yield break at the end of each generator method.

Anonymous delegates

As a precursor to the lambda functions introduced in C# 3.0, C#2.0 added anonymous delegates. These provide closure-like functionality to C#.[3] Code inside the body of an anonymous delegate has full read/write access to local variables, method parameters, and class members in scope of the delegate, excepting out and ref parameters. For example:-

int SumOfArrayElements(int[] array)
{
    int sum = 0;
    Array.ForEach(array,
        delegate(int x)
        {
            sum += x;
        }
    );
    return sum;
}

Unlike some closure implementations, each anonymous delegate instance has access to the same relative memory location for each bound variable, rather than to the actual values at each creation. See a fuller discussion of this distinction.

Delegate covariance and contravariance

Conversions from method groups to delegate types are covariant and contravariant in return and parameter types, respectively.[4]

The accessibility of property accessors can be set independently

Example:

string status = string.Empty;

public string Status
{
    get { return status; }             // anyone can get value of this property,
    protected set { status = value; }  // but only derived classes can change it
}

Nullable value types

Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.

Nullable value types received an improvement at the end of August 2005, shortly before the official launch, to improve their boxing characteristics: a nullable variable which is assigned null is not actually a null reference, but rather an instance of struct Nullable<T> with property HasValue equal to false. When boxed, the Nullable instance itself is boxed, and not the value stored in it, so the resulting reference would always be non-null, even for null values. The following code illustrates the corrected flaw:

int? i = null;
object o = i;
if (o == null)
    System.Console.WriteLine("Correct behaviour - runtime version from September 2005 or later");
else
    System.Console.WriteLine("Incorrect behaviour - pre-release runtime (from before September 2005)");

When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal. The late nature of this fix caused some controversy[5] , since it required core-CLR changes affecting not only .NET2, but all dependent technologies (including C#, VB, SQL Server 2005 and Visual Studio 2005).

Null-coalescing operator

The ?? operator is called the null coalescing operator and is used to define a default value for nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.[6]

object nullObj = null; 
object obj = new Object(); 
return nullObj ?? obj; // returns obj

The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:

int? i = null;
int j = i ?? 0; // If i is not null, initialize j to i. Else (if i is null), initialize j to 0.

References

  1. ^ "An Introduction to C# Generics". Microsoft. January 2005. Retrieved June 18, 2009.
  2. ^ "yield". C# Language Reference. Microsoft. Retrieved 2009-04-26.
  3. ^ "Anonymous Methods (C#)". C# Programming Guide. Microsoft. Retrieved June 18, 2009.
  4. ^ "Covariance and Contravariance in Delegates (C#)". C# Programming Guide. Microsoft. Retrieved June 18, 2009.
  5. ^ Somasegar (August 11, 2005). "Nulls not missing anymore". Somasegar's WebLog. MSDN. Retrieved 2008-11-05.
  6. ^ "?? Operator". C# Reference. Microsoft. Retrieved 2008-11-23.

Read other articles:

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Januari 2023. Asia Pacific Scout RegionPemilikWorld Organization of the Scout MovementMarkas besarMakati City, FilipinaLokasiAsia PacificAnggota24.7 jutaAPRSC ChairmanJejomar BinayRegional DirectorAbdullah RasheedSitus webhttp://www.scout.org/asia-pacific Wilay...

 

George IIGeorge II tahun 1727 ketika ia naik takhta.Raja Britania RayaRaja IrlandiaElektor HannoverBerkuasa22 Juni 1727 – 25 Oktober 1760Penobatan22 Oktober 1727PendahuluGeorge IPenerusGeorge IIIInformasi pribadiPemakaman11 November 1760Westminster Abbey, LondonWangsaHannoverNama lengkapGeorge AugustusJerman: Georg Augustcode: de is deprecated AyahGeorge I, Raja Britania RayaIbuSophia DorotheaPasanganCaroline dari AnsbachAnakFrederick, Pangeran WalesAnne, Putri Royal dan Putri OrangeAmeliaC...

 

King of Scotland from 1249 to 1286 Alexander IIICoronation of King Alexander on Moot Hill, Scone. He is being greeted by the ollamh rígh, the royal poet, who is addressing him with the proclamation Benach De Re Albanne (= Beannachd Dé Rígh Alban, God Bless the King of Scotland); the poet goes on to recite Alexander's genealogy. By Alexander's side is Maol Choluim II, Earl of Fife, holding the sword.King of ScotlandReign6 July 1249 – 19 March 1286Coronation13 July 1249PredecessorAlexander...

Scientist in the field of astronomy A voting session is conducted in 2006 International Astronomical Union's general assembly for determining a new definition of a planet An astronomer is a scientist in the field of astronomy who focuses their studies on a specific question or field outside the scope of Earth. They observe astronomical objects such as stars, planets, moons, comets and galaxies – in either observational (by analyzing the data) or theoretical astronomy. Examples of topics or ...

 

Suster Misi Abdi Roh Kudus adalah salah satu tarekat atau kongregasi religius atau ordo keagamaan Katolik yang mempunyai nama resmi: Servae Spiritus Sanctus, yang berarti: Misi Abdi Roh Kudus. Kongregasi ini didirikan oleh Santo Arnoldus Janssen, pada tanggal 8 Desember 1889,[1] bersama dengan dua orang rekan biarawati yakni Beata Maria Helena Stollenwerk dan Beata Josefa Hendrina Stenmanns, di Steyl, suatu tempat di negara Belanda yang berada di wilayah perbatasan dengan negara Jerm...

 

Questa voce sull'argomento cardinali spagnoli è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Joaquín Fernández de Portocarrerocardinale di Santa Romana ChiesaRitratto del cardinale Fernández, opera di Antoine de Favray  Incarichi ricoperti Viceré di Napoli (1728) Patriarca titolare di Antiochia (1735-1743) Cardinale presbitero dei Santi Quattro Coronati (1743-1747) Prefetto della Congregazione per le Indulgenze e le Sacre Reliquie (1748-1760...

SMA Negeri 16 SurabayaInformasiJenisNegeriAkreditasiA[1]Nomor Statistik Sekolah301056021001Kepala SekolahDrs. Moch. Usman, M.Pd.Jumlah kelas33 kelasJurusan atau peminatanIPA dan IPSRentang kelasX MIA, X IIS, XI MIA, XI IIS, XII MIA, XII IISKurikulumKurikulum 2013StatusSekolah NasionalAlamatLokasiJalan Raya Prapen, Surabaya, Jawa Timur, IndonesiaTel./Faks.031-8415492/031-8430673Situs web[http://www.sman16-sby.sch.idMotoMotoCERDAS BERSINAR Sekolah Menengah Atas Negeri 16 ...

 

Questa voce sull'argomento politici greci è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Epameinondas Deligiorgis Primo ministro della GreciaDurata mandato1º novembre 1865 –15 novembre 1865 Capo di StatoGiorgio I PredecessoreAlexandros Koumoundouros SuccessoreDimitrios Voulgaris Durata mandato25 novembre 1865 –11 dicembre 1865 Capo di StatoGiorgio I PredecessoreAlexandros Koumoundouros SuccessoreMpenizelos Roufōs Dur...

 

† Человек прямоходящий Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапсиды�...

Pour les articles homonymes, voir NBC. National Broadcasting Company (NBC) Type Ancien réseau de radiodiffusionRéseau de télévision Pays États-Unis Fondateurs David Sarnoff Slogan « Every Day is Full of Color »« More Colorful » Siège social GE Building Propriétaire NBCUniversal Lancement 1926 Dissolution 2003 (radio) Format d'image 480i (16:9 SDTV)1080i (HDTV) Indicatif NBC Signification de l'indicatif National Broadcasting Company Site web nbc.com modifier - m...

 

Disambiguazione – Se stai cercando altri significati, vedi Sansoni (disambigua). Sansoni Stato Italia Fondazione1873 a Firenze Fondata daGiulio Cesare Sansoni GruppoGruppo Mondadori SettoreEditoria Modifica dati su Wikidata · Manuale Sansoni è una casa editrice italiana fondata nel 1873 da Giulio Cesare Sansoni e con sede a Firenze. Indice 1 Storia 2 Archivio storico 3 Bibliografia 4 Altri progetti 5 Collegamenti esterni Storia L'attività editoriale si rivolse fino agli an...

 

American baseball player (born 1981) Baseball player Anthony ReyesReyes with the St. Louis CardinalsPitcherBorn: (1981-10-16) October 16, 1981 (age 42)Whittier, California, U.S.Batted: RightThrew: RightMLB debutAugust 9, 2005, for the St. Louis CardinalsLast MLB appearanceMay 22, 2009, for the Cleveland IndiansMLB statisticsWin–loss record13–26Earned run average5.12Strikeouts205 Teams St. Louis Cardinals (2005–2008) Cleveland Indians (2008–2009) Care...

German composer, musicologist, opera director and conductor (1943–2021) Udo ZimmermannZimmermann in 2006Born6 October 1943Dresden, Saxony, GermanyDied22 October 2021(2021-10-22) (aged 78)Dresden, GermanyEducation Dresdner Kreuzchor Musikhochschule Dresden Occupations Composer Musicologist Conductor Opera director Organizations Musikhochschule Dresden Dresden Center for Contemporary Music Leipzig Opera Deutsche Oper Berlin Udo Zimmermann (6 October 1943[1] – 22 October 2021 ...

 

Exterior of an inpatient hospice unit In the United States, hospice care is a type and philosophy of end-of-life care which focuses on the palliation of a terminally ill patient's symptoms. These symptoms can be physical, emotional, spiritual or social in nature. The concept of hospice as a place to treat the incurably ill has been evolving since the 11th century. Hospice care was introduced to the United States in the 1970s in response to the work of Cicely Saunders in the United Kingdom. T...

 

City in Barton County, Kansas City in Kansas, United StatesHoisington, KansasCityHoisington High School (2017)Location within Barton County and KansasKDOT map of Barton County (legend)Coordinates: 38°31′2″N 98°46′42″W / 38.51722°N 98.77833°W / 38.51722; -98.77833[1]CountryUnited StatesStateKansasCountyBartonFounded1886Incorporated1887Named forAndrew HoisingtonArea[2] • Total1.16 sq mi (3.00 km2) • Land1...

Civic holiday in the USA This article is about the American civic holiday. For the Quebec holiday, see National Patriots' Day. For the anniversary of September 11, 2001, see Patriot Day. For the 2016 motion picture about the Boston Marathon bombing, see Patriots Day (film). Patriots' DayStatue of the Lexington Minuteman on the Lexington Green in Lexington, MassachusettsObserved by Massachusetts Maine Florida (on April 19) Wisconsin (on April 19) Connecticut North Dakota TypeHistoricalCel...

 

UK parliamentary constituency in England, created 1983 Barnsley Centralborough constituencyfor the House of CommonsBoundary of Barnsley Central in South YorkshireLocation of South Yorkshire within EnglandCountySouth YorkshirePopulation85,714 (2011 census)[1]Electorate64,229 (December 2019)[2]BoroughBarnsleyMajor settlementsBarnsley, RoystonCurrent constituencyCreated1983Member of ParliamentDan Jarvis[3] (Labour)SeatsOneCreated fromBarnsley, Wakefield Barnsley Central i...

 

1392–1865 Korean royal records Diary of King Yeonsan redirects here. For the Korean film, see Diary of King Yeonsan (film). Veritable Records of the Joseon DynastyVeritable Records of JeongjoKorean nameHangul조선왕조실록Hanja朝鮮王朝實錄Revised RomanizationJoseon Wangjo SillokMcCune–ReischauerChosŏn Wangjo SillokNorth Korean nameHangul조선봉건왕조실록[1]Hanja朝鮮封建王朝實錄Revised RomanizationJoseon Bonggeon Wangjo SillokMcCune–ReischauerChosŏn Bon...

Highest civilian honor of Barbados For other uses, see Order of the National Hero (disambiguation). Order of National Heroes Awarded by President of BarbadosTypeNational HonourEstablished20 April 1998; 26 years ago (20 April 1998)CriteriaAt the pleasure of the president with the recommendation of the prime ministerStatusCurrently constitutedFounderParliament of BarbadosChancellorSandra Mason(President of Barbados)SecretaryVacantClassesMember (National Hero)StatisticsFirst inducti...

 

Politics of Sierra Leone Constitution Human rights Executive President (list) Julius Maada Bio Vice-President Mohamed Juldeh Jalloh Chief Minister (list) Jacob Jusu Saffa Cabinet Legislative Parliament Speaker: Abass Bundu Members of Parliament Judiciary Supreme Court Chief Justice: A. H. Charm Human rights Elections Political parties Recent elections General: 201220182023 Administrative divisions Provinces Districts Chiefdoms Foreign relations Ministry of Foreign Affairs and International C...