Chapter1:GettingstartedwithC# Language

No Comments

VersionReleaseDate

1.02002-01-01

1.22003-04-01

2.02005-09-01

3.02007-08-01

4.02010-04-01

5.02013-06-01

6.02015-07-01

7.02017-03-07

Section1.1:Creatinganewconsoleapplication(VisualStudio)

  1. OpenVisualStudio
  2. Inthetoolbar,gotoFile→NewProject
  3. SelecttheConsoleApplicationprojecttype
  4. OpenthefileProgram.csintheSolutionExplorer
  5. AddthefollowingcodetoMain():

publicclassProgram

{

publicstaticvoidMain()

{

//Printsamessagetotheconsole.

System.Console.WriteLine(“Hello,World!”);

/*Waitfortheusertopressakey.Thisisacommon

waytopreventtheconsolewindowfromterminating

anddisappearingbeforetheprogrammercanseethecontents

ofthewindow,whentheapplicationisrunviaStartfromwithinVS.*/

System.Console.ReadKey();

}

}

6. In the toolbar, click Debug->StartDebuggingor hit F5 or ctrl+F5(running without debugger) to run the program.

LiveDemoonideone

Explanation

classProgramis a class declaration. The class Programcontains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class.

  • However,theProgramclasshasonlyonemethod:Main. staticvoidMain()definestheMainmethod,whichistheentrypointforallC#programs.TheMainmethod stateswhattheclassdoeswhenexecuted.OnlyoneMainmethodisallowedperclass.
  • System.Console.WriteLine(“Hello,world!”);methodprintsagivendata(inthisexample,Hello,world!)asanoutputintheconsolewindow.
  • System.Console.ReadKey(),ensuresthattheprogramwon’tcloseimmediatelyafterdisplayingthemessage. Itdoesthisbywaitingfortheusertopressakeyonthekeyboard.Anykeypressfromtheuserwillterminate theprogram.Theprogramterminateswhenithasfinishedthelastlineofcodeinthemain()method. Usingthecommandline TocompileviacommandlineuseeitherMSBuildorcsc.exe(theC#compiler),bothpartofthe MicrosoftBuildTools package. Tocompilethisexample,runthefollowingcommandinthesamedirectorywhereHelloWorld.csislocated:

%WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exeHelloWorld.cs

Itcanalsobepossiblethatyouhavetwomainmethodsinsideoneapplication.Inthiscase,youhavetotellthe compilerwhichmainmethodtoexecutebytypingthefollowingcommandintheconsole.(supposeClassClassAalso has a main method in the same HelloWorld.csfile in HelloWorld namespace)

%WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exeHelloWorld.cs/main:HelloWorld.ClassA

whereHelloWorldis namespace

Note:Thisisthepathwhere.NETframeworkv4.0islocatedingeneral.Changethepathaccordingtoyour.NETversion. In addition, the directory might be frameworkinstead of framework64if you’re using the 32-bit .NET Framework. From theWindowsCommandPrompt,youcanlistallthecsc.exeFrameworkpathsbyrunningthefollowingcommands(thefirst for 32-bit Frameworks):

dir%WINDIR%\\Microsoft.NET\\Framework\\csc.exe/s/b dir%WINDIR%\\Microsoft.NET\\Framework64\\csc.exe/s/b

ThereshouldnowbeanexecutablefilenamedHelloWorld.exeinthesamedirectory.Toexecutetheprogram

fromthecommandprompt,simplytypetheexecutable’snameandhit    

asfollows:

HelloWorld.exe

Thiswillproduce:Hello,world!

Youmayalsodoubleclicktheexecutableandlaunchanewconsolewindowwiththemessage”Hello,world!”

Section 1.2: Creating a new project in Visual Studio (console application)andRunningitinDebugmode

  1. DownloadandinstallVisualStudio. Visual Studio can be downloaded from VisualStudio.com. The Communityeditionissuggested,firstbecauseitisfree,andsecondbecauseitinvolvesallthegeneral features and can be extended further.
  2. OpenVisualStudio.
  3. Welcome.GotoFile→New→Project.

4. ClickTemplates→VisualC#→ConsoleApplication

5. AfterselectingConsoleApplication,Enteranameforyourproject,andalocationtosaveandpress . Ok Don’t worry about the Solution name.

6. Projectcreated.Thenewly createdprojectwill looksimilarto:

                  

(Alwaysusedescriptivenamesforprojectssothattheycaneasilybedistinguishedfromotherprojects.Itis recommended not to use spaces in project or class name.)

7. Writecode.YoucannowupdateyourProgram.cstopresent”Helloworld!”totheuser.

usingSystem;

namespaceConsoleApplication1

{

publicclassProgram

{

publicstaticvoidMain(string[]args)

{

}

}

}

AddthefollowingtwolinestothepublicstaticvoidMain(string[]args)objectinProgram.cs:(make sureit’sinsidethebraces)

Console.WriteLine(“Helloworld!”);

Console.Read();

WhyConsole.Read()?Thefirstlineprintsoutthetext”Helloworld!”totheconsole,andthesecondlinewaitsforasinglecharactertobeentered;ineffect,thiscausestheprogramtopauseexecutionsothatyou’re abletoseetheoutputwhiledebugging.WithoutConsole.Read();,whenyoustartdebuggingtheapplication itwilljustprint”Helloworld!”totheconsoleandthenimmediatelyclose.Yourcodewindowshouldnowlook like the following:

usingSystem;

namespaceConsoleApplication1

{

publicclassProgram

{

publicstaticvoidMain(string[]args)

{

Console.WriteLine(“Helloworld!”);

Console.Read();

}

}

}

8. Debugyourprogram.PresstheStartButtononthetoolbarnearthetopofthewindow

orpress on your keyboard to run your application. If the button is not present, you can run the program fromthe top menu: Debug→StartDebugging. The program will compile and then open a console window. It shouldlooksimilartothefollowingscreenshot:

9. Stop the program. Toclosetheprogram,justpressanykeyonyourkeyboard.TheConsole.Read()we addedwasforthissamepurpose.Anotherwaytoclosetheprogramisbygoingtothemenuwherethe Start buttonwas,and clickingonthe    Stop      button.

Section1.3:Creating anewprogram using.NETCore

Firstinstallthe.NETCoreSDKbygoingthroughtheinstallationinstructionsfortheplatformofyourchoice: Windows

  • OSX
  • Linux
  • Docker

Aftertheinstallationhascompleted,openacommandprompt,orterminalwindow.

hello_world.csproj

  1. Createanewdirectorywithmkdirhello_worldandchangeintothenewlycreateddirectorywithcd hello_world.
  2. Create a new console application with dotnetnewconsole. This will produce two files:

hello_world.csproj

<ProjectSdk=”Microsoft.NET.Sdk”>

<PropertyGroup>

<OutputType>Exe</OutputType>

<TargetFramework>netcoreapp1.1</TargetFramework>

</PropertyGroup>

</Project>

0 Program3.CS

namespacehello_world

{

classProgram

{

staticvoidMain(string[]args)

{

Console.WriteLine(“HelloWorld!”);

}

}

}

3. Restoretheneededpackageswithdotnetrestore.

4.OptionalBuildtheapplicationwithdotnetbuildforDebugordotnetbuild-cReleaseforRelease.dotnetrunwill also run the compiler and throw build errors, if any are found.

5. RuntheapplicationwithdotnetrunforDebugordotnetrun

.\bin\Release\netcoreapp1.1\hello_world.dllforRelease.

CommandPromptoutput

Section1.4:CreatinganewprogramusingMono

FirstinstallMonobygoingthroughtheinstallinstructionsfortheplatformofyourchoiceasdescribedintheir installation section.

MonoisavailableforMacOSX,WindowsandLinux.

Afterinstallationisdone,createatextfile,nameitHelloWorld.csandcopythefollowingcontentintoit:

publicclassProgram

{

publicstaticvoidMain()

{

System.Console.WriteLine(“Hello,world!”);

System.Console.WriteLine(“Pressanykeytoexit..”);

System.Console.Read();

}

}

IfyouareusingWindows,runtheMonoCommandPromptwhichisincludedintheMonoinstallationandensures thatthenecessaryenvironmentvariablesareset.IfonMacorLinux,openanewterminal.

Tocompilethenewlycreatedfile,runthefollowingcommandinthedirectorycontainingHelloWorld.cs:

mcs-out:HelloWorld.exeHelloWorld.cs

TheresultingHelloWorld.execanthenbeexecutedwith:

monoHelloWorld.exe

whichwillproducetheoutput:

Hello,world!

Pressanykeytoexit..

Section1.5:CreatinganewqueryusingLinqPad

LinqPadisagreattoolthatallowsyoutolearnandtestfeaturesof.Netlanguages(C#,F#andVB.Net.)

  1. Install LinqPad
  2. CreateanewQuery( Ctrl+N )

3. Underlanguage,select”C#statements”

4. Typethefollowingcodeandhitrun(   F5    )

stringhw=”HelloWorld”;

hw.Dump();//orConsole.WriteLine(hw);

5. Youshouldsee”HelloWorld”printedoutintheresultsscreen.

6. Now that you have created your first .Net program, go and check out the samples included in LinqPad via the “Samples” browser. There are many great examples that will show you many different features of the .Net languages.

Notes:

  1. Ifyouclickon”IL”,youcaninspecttheILcodethatyour.netcodegenerates.Thisisagreatlearningtool.

2. WhenusingLINQtoSQLorLinqtoEntitiesyoucaninspecttheSQLthat’sbeinggeneratedwhichis anothergreatwaytolearnaboutLINQ.

Section 1.6:Creatinganew projectusingXamarinStudio

  1. DownloadandinstallXamarinStudio Community.
  2. OpenXamarinStudio.
  3. ClickFile→New→Solution.

4. Click.NET→ConsoleProjectandchooseC#.

5.Click  Next     toproceed.

6. EntertheProjectNameand   Browse… foraLocationtoSaveandthenclick  Create.                              .

7. Thenewlycreatedprojectwilllooksimilarto:

8. ThisisthecodeintheTextEditor:

usingSystem;

namespaceFirstCsharp

{

publicclassMainClass

{

publicstaticvoidMain(string[]args)

{

Console.WriteLine(“HelloWorld!”);

Console.ReadLine();

}

}

}

9. Torunthecode,press        F5              orclickthePlayButtonasshownbelow:

10. FollowingistheOutput:

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments