Learning C# as a python programmer

Learning a new programming language can be difficult at first. While the basic concept of object oriented programming is the same across languages, the syntax can be quite different. This post will go over the basic differences between python and C#, focusing on basic syntax and typing.

Comments

Python:
single line comments start with #.
multi-line comments start with ”’ and end with ”’ on their own lines

# this is a comment
'''
this is a
multi-line comment
'''

C#:
single line comments start with //.
multi-line comments start with /* and end with */

// this is a comment
/*
this is a multi-line comment
*/

Ending statements

Python:
statements end with a new line. statements can only wrap into the next line if there is an open parentheses or bracket.

print("this is long but it's okay
   because of the parentheses")

C#:
statements end with a semi-colon. any statement can be wrapped into multiple lines.


Console.WriteLine("this is long
   but the statement won't end
   until the semi-colon);

Separating blocks of code

Python:
uses indentation to separate blocks of code.



if a < b
   foo(a)
else
   foo(b)
   bar(b)

C#:
uses {} to separate blocks of code. braces can be omitted if the block is one line, but if/else statements should always match in their use of braces

if (a < b) {
   foo(a);
else {
   foo(b);
   bar(b);
}

variable types

Python:
types do not have to be explicitly declared. python will automatically convert types in some situations



x = 1
y = "hello"

C#:
types must be explicitly declared. If you initialize the variable in the same line as declaration, you can use the “var” keyword to have the compiler determine the type.

int x;
var y = "hello"

List types

Python:
can create a list or array without declaring the type. can have lists or arrays of multiple types


myList = [1, "two", 3.5]

C#:
must declare the type of variable in a list or array. cannot have lists or arrays of multiple types (unless they are of classes derived from the same parent class)

var myList = new List<int>();
myList.Add(1);

Comparing

Python:
use = to compare values in an if.


if a = b

C#:
use == to compare values in an if. surround values being compared by ()

if (a == b)

Looping

Python:
loop using

for i in range(0,10)

C#:
loop using

for (int i = 0; i < 10; i++)

iterating

Python:
iterate using

for item in myList

C#:
iterate using

foreach (var item in myList)



Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *