Category Archives: C# Programming

Chapter40:AccessModifiers

Section40.1:AccessModifiersDiagrams Hereareallaccessmodifiersinvenndiagrams,frommorelimitingtomoreaccessible: AccessModifier                                      Diagram Belowyoucouldfindmoreinformation. Section40.2:public Thepublickeywordmakesaclass(includingnestedclasses),property,methodorfieldavailabletoevery consumer: publicclassFoo() { publicstringSomeProperty{get;set;} publicclassBaz { publicintValue{get;set;} } } publicclassBar() { publicBar() { varmyInstance=newFoo(); varsomeValue=foo.SomeProperty;varmyNest edInstance=newFoo.Baz();…
Continue reading

Chapter39:ConstructorsandFinalizers

Constructorsaremethodsinaclassthatareinvokedwhenaninstanceofthatclassiscreated.Theirmain responsibility is to leave the new object in a useful and consistent state. Destructors/Finalizersaremethodsinaclassthatareinvokedwhenaninstanceofthatisdestroyed.InC#theyare rarely explicitely written/used. Section39.1:Staticconstructor Astaticconstructoriscalledthefirsttimeanymemberofatypeisinitialized,astaticclassmemberiscalledora static method. The…
Continue reading

Chapter38:Nullabletypes

Section38.1:Initialisinganullable Fornullvalues: Nullable<int>i=null; Or: int?i=null; Or: vari=(int?)null; Fornon-nullvalues: Nullable<int>i=0; Or: int?i=0; Section38.2:CheckifaNullablehasavalue int?i=null; if(i!=null) { Console.WriteLine("iisnotnull"); } else { Console.WriteLine("iisnull"); } Whichisthesameas: if(i.HasValue)…
Continue reading

Chapter37:Casting

Section37.1:Checkingcompatibilitywithoutcasting Ifyouneedtoknowwhetheravalue'stypeextendsorimplementsagiventype,butyoudon'twanttoactuallycast it as that type, you can use the isoperator. if(valueisint) { Console.WriteLine(value+"isanint"); } Section37.2:Castanobjecttoabasetype Giventhefollowingdefinitions: publicinterfaceIMyInterface1 { stringGetName(); } publicinterfaceIMyInterface2 {…
Continue reading

Chapter36:TypeConversion

Section36.1:ExplicitTypeConversion usingSystem; namespaceTypeConversionApplication { classExplicitConversion { staticvoidMain(string[]args) { doubled=5673.74; inti; //castdoubletoint. i=(int)d; Console.WriteLine(i); Console.ReadKey(); } } } Section36.2:MSDNimplicitoperatorexample classDigit { publicDigit(doubled){val=d;} publicdoubleval; //User-definedconversionfromDigittodouble…
Continue reading

Chapter 35:Dynamic type

Section35.1:Creatingadynamicobjectwithproperties usingSystem; usingSystem.Dynamic; dynamicinfo=newExpandoObject(); info.Id=123; info.Another=456; Console.WriteLine(info.Another); //456 Console.WriteLine(info.DoesntExist); //ThrowsRuntimeBinderException Section35.2:Creatingadynamicvariable dynamicfoo=123; Console.WriteLine(foo+234); //357             Console.WriteLine(foo.ToUpper()) //RuntimeBinderException,sinceintdoesn'thaveaToUppermethod foo="123"; Console.WriteLine(foo+234); //123234 Console.WriteLine(foo.ToUpper()): //NOWASTRING Section35.3:Returningdynamic usingSystem;…
Continue reading

Chapter34:Anonymoustypes

Section34.1:Anonymousvsdynamic Anonymoustypesallowthecreationofobjectswithouthavingtoexplicitlydefinetheirtypesaheadoftime,while maintaining static type checking. varanon=new{Value=1}; Console.WriteLine(anon.Id);//compiletimeerror Conversely, dynamichasdynamictypechecking, optingforruntimeerrors,insteadofcompile-timeerrors. dynamicval="foo"; Console.WriteLine(val.Id);//compiles,butthrowsruntimeerror Section 34.2: Creatingan anonymoustype Sinceanonymoustypesarenotnamed,variablesofthosetypesmustbeimplicitlytyped(var). varanon=new{Foo=1,Bar=2}; //anon.Foo==1 //anon.Bar==2 Ifthemembernamesarenotspecified,theyaresettothenameoftheproperty/variableusedtoinitializethe object.…
Continue reading

Chapter33:Aliasesofbuilt-intypes

Section33.1:Built-InTypesTable Thefollowingtableshowsthekeywordsforbuilt-in C#types,whicharealiasesofpredefinedtypesintheSystem namespaces. C#Type.NETFrameworkType bool                  System.Boolean byte                  System.Byte sbyte                  System. SByte char          System.Char decimalSystem.Decimal doubleSystem.Double float                  System.Singleint                   System.Int32 uint            System.UInt32…
Continue reading

Chapter32:Built-inTypes

Section32.1:Conversionofboxedvaluetypes Boxedvaluetypescanonlybeunboxedintotheiroriginal Type,evenifaconversionofthetwoTypesisvalid,e.g.: objectboxedInt=(int)1;//intboxedinanobject longunboxedInt1=(long)boxedInt;//invalidcast This canbeavoidedby firstunboxingintothe originalType,e.g.: longunboxedInt2=(long)(int)boxedInt;//valid Section32.2:Comparisonswithboxedvaluetypes Ifvaluetypesareassignedtovariablesoftypeobjecttheyareboxed-thevalueisstoredinaninstanceofa System.Object.Thiscanleadtounintendedconsequenceswhencomparingvalueswith==,e.g.: objectleft=(int)1;                 //intinanobjectbox objectright=(int)1;//intinanobjectbox varcomparison1=left==right; //false This canbeavoidedbyusingtheoverloadedEqualsmethod,whichwillgivetheexpectedresult. varcomparison2=left.Equals(right);//true Alternatively,thesamecouldbedonebyunboxingtheleftandrightvariablessothattheintvaluesare compared:…
Continue reading

Chapter31:ValuetypevsReferencetype

Section31.1:Passingbyreferenceusingrefkeyword Fromthedocumentation InC#,argumentscanbepassedtoparameterseitherbyvalueorbyreference.Passingbyreference enablesfunctionmembers,methods,properties,indexers,operators,andconstructorstochangethe valueoftheparametersandhavethatchangepersistinthecallingenvironment.Topassaparameterby reference, use the refor outkeyword. Thedifferencebetweenrefandoutisthatoutmeansthatthepassedparameterhastobeassignedbeforethe functionends.incontrastparameterspassedwithrefcanbechangedorleftunchanged. usingSystem; classProgram { staticvoidMain(string[]args) { inta=20; Console.WriteLine("InsideMain-BeforeCallee:a={0}",a); Callee(a); Console.WriteLine("InsideMain-AfterCallee:a={0}",a); Console.WriteLine("InsideMain-BeforeCalleeRef:a={0}",a); CalleeRef(refa);…
Continue reading