python vs C# Differences

Let's have a brief comparison of C# syntax to python syntax. Pause the video to compare snippets if you want to learn more about them.

python vs C# Differences

Let's have a brief comparison of C# syntax to python syntax. Pause the video to compare snippets if you want to learn more about them.

Syntax Difference Intro

While Autodesk doesn't officially support Python, translating C# code from Revit documentation into Python is not complicated.

Understanding the differences between these two languages can help you easily translate examples and take full advantage of resources available in C#. You will often find answers on C# forums and blogs, so it's a useful skill to have.

Let's explore the main difference between Python and C#, from syntax to structure, and other concepts.

Code Structure

One of the most immediate differences between Python and C# is how they define code blocks.

  • Python uses indentation(4 spaces/tab) to define code blocks

  • C# uses curly braces {} to define code blocks

This often makes Python code feel cleaner in comparison to C#.


You will also notice that all statements in C# end with a ; (semi-colon), while in python we don't need anything in the end of the line.

// CODE STRUCTURE
void MyFunction(int arg)
{
    if (arg > 0)
    {
        Console.WriteLine('More');
    }
    else
    {
        Console.WriteLine('Less'

# CODE STRUCTURE
def my_function(arg):

    if arg > 0:

        print('More')

    else:

        print('Less')

Variables

In Python, variables are easy—you just assign them a value, and Python figures out the type for you. No need to declare types upfront. For example:

But in C#, every time you create a variable, you have to define its type. So you would do something like this:

var myNum = 50;  // Non-Defined Data Type
int myNum = 50;  // Defined Data Type

// More Types
int count = 10;
double length = 5.50;
string name = "Wall"

my_num = 50  # Non-Defined Type
my_num: int = 50  # Defined Type

# More Types
count = 10
length = 5.50
name = "Wall"

💡 In C#, you can also use the var keyword, which lets the compiler figure out the type for you, but it’s still stricter than Python in that it requires you to stick to one type for that variable.

Variables - FEC

Now let’s look at something more specific—the FilteredElementCollector, which is a Revit API class you’ll use a lot. There’s gonna be a whole module on how to use it properly, but let’s see how it compares in Python and C#.

// Revit API Variable
using Autodesk.Revit.DB;
FilteredElementCollector collector = new FilteredElementCollector(doc

# Revit API Variable
from Autodesk.Revit.DB import *
collector = FilteredElementCollector(doc)

You will notice that we do imports differently between C# and Python.

Also since we need to use FilteredElementCollector's constructor, you will notice that C# needs to use 'new' keyword. In python we just use constructor like a method.

Operators

Let’s move on to operators. These are the basics—addition, subtraction, multiplication, and so on. The syntax is pretty similar between Python and C#.


There are not so many differences after all:

  • C# needs to define type for all variables

  • C# has its own Math module

  • True/False is lower case in C# (true, false)

  • C# uses symbols instead of words for and/or/not

// Arithmetic Operators
int a = 10;
int b = 3;

int sum        = a + b;    // Addition
int difference = a - b;    // Subtraction
int product    = a * b;    // Multiplication
double quotient = (double) a / b;   // Division (cast to double)
int modulus    = a % b;    // Modulus
double power   = Math.Pow(a, b);    // Exponentiation using Math.Pow
double floor_div = Math.Floor((double) a / b);  // Floor Division


// Comparison Operators
bool isEqual        = (a == b);  // Equal
bool isNotEqual     = (a != b);  // Not Equal
bool isGreater      = (a > b);   // Greater Than
bool isLess         = (a < b);   // Less Than
bool isGreaterEqual = (a >= b);  // Greater Than or Equal
bool isLessEqual    = (a <= b);  // Less Than or Equal


// Logical Operators
bool c = true;
bool d = false;

bool andResult = c && d;   // Logical AND
bool orResult  = c || d;   // Logical OR
bool notResult = !c;       // Logical NOT

# Arithmetic Operators
a = 10
b = 3

add        = a + b    # Addition
difference = a - b    # Subtraction
product    = a * b    # Multiplication
quotient   = a / b    # Division
modulus    = a % b    # Modulus
power      = a ** b   # Exponentiation
floor_div  = a // b   # Floor Division


# Comparison Operators
is_equal        = (a == b)  # Equal
is_not_equal    = (a != b)  # Not Equal
is_greater      = (a > b)   # Greater Than
is_less         = (a < b)   # Less Than
is_greater_equal = (a >= b) # Greater Than or Equal
is_less_equal    = (a <= b) # Less Than or Equal


# Logical Operators
c = True
d = False

and_result = c and d    # Logical AND
or_result  = c or d     # Logical OR
not_result = not c      # Logical NOT

If Statements

Now let's look at logical statements. You will notice that it's not so different afterall.

elif is called else if and we don't need colons after the if statements.

The other difference is just in using curly braces and semi-colons.

int myNumber = 5;

if (myNumber > 10)
{
    Console.WriteLine("Number is more than 10");
}
else if (myNumber == 5)
{
    Console.WriteLine("Number is 5");
}
else
{
    Console.WriteLine("Number is less than 5"

my_num = 5

if my_num > 10:
    print("Number is more than 5")
elif my_num == 5:
    print("Number is 5")
else:
    print("Number is less than 5")

Loops

Python and C# both have for-loops and while-loops, but the syntax is a little different. But you will notice the biggest difference in how range is used.

In C# you always need to define start, end point and how to increment the number. In python we have default values, so it can look much simpler. But we can also provide more arguments if we need more controls.

Also symbols like -= and += becomes double or ++.

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}


// while Loop
int count = 5;
while (count > 0)
{
    Console.WriteLine(count);
    count

# for Loop
for i in range(10):
    print(i)


# while Loop
count = 5
while count > 0:
    print(count)
    count -= 1

Function

Now let's talk about functions. In general it's quite similar, except for the defining types.

First let's have a look at functions that do not return anything. In python we just use def keyword and write our function.

In C# you start defining your function by telling what is the Type of element that is being returned. And when functions don't return anything, we use the keyword void, which shows that this function has no returning value.

void MyFunction()
{
    Console.WriteLine("Simple Function"

def my_function():
    print('Simple Function')

If you want to create a function that returns something, you need to declare the Type of the returned object from this function. In the beginning of the function you write the Type name of the returned object, in this example below you can see word View instead of void.

Also you will notice that you need to define types of all parameters in your function. This will ensure that users provide the right types, but also provides better debugging capabilities.

It's possible to define type-hinting for functions in python too with a syntax that looks like comment. This will actually tell your code-editor what types of elements have to be provided and returned.

void MyFunction()
{
    Console.WriteLine("Simple Function");
}


View MyFunction(View view, int x)
{
    Console.WriteLine("View Name: {0}", view.Name);
    return view

def my_function():
    print('Simple Function')


def my_function(view, x):
    # type: (View, int) -> View
    print("View Name: {}".format(view.Name))
    return view

Class

Classes are simple. Once you know the difference in functions, the same logic applies to Class and methods.

The only difference is that there is no need to use first parameter - self in your methods. C# already includes it by default and uses word this to refer to itself.

class MyClass
{
    View MyFunction(View view, int x)
    {
        // Method Body
        return view

class MyClass:
    def MyFunction(self, view, x):
        # Method Body
        return view

Inheritance

As you know in programming we can inherit classes and build new ones based on that. That's like using Template in Revit…

The main difference is the syntax. In C# they use colon after the class name and specify class to inherit from. In python we use parenthesis to do that.

public class BaseClass
{
    public void BaseMethod() { }
}


public class DerivedClass : BaseClass
{
    public void DerivedMethod

class BaseClass:
    def base_method(self):
        pass


class DerivedClass(BaseClass):
    def derived_method(self):
        pass

Error Handling

Next, let's have a look how to handle errors, and you will see that they are very similar. The biggest difference is that C# uses keyword catch instead of except.

The rest is pretty much the same with the usual syntax differences.

try
{
    // Code that may throw an exception
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error occurred: " + ex.Message);
}
finally
{
    Console.WriteLine("This will execute regardless of exception."

try:

    # Code That might give exception
    result = 10 / 0
    
except ZeroDivisionError as e:  # Specific Exception

    print("Error occurred:", e)

finally:

    print("This will execute regardless of exception.")

Context Manager

As you know in programming we have a concept called Context Manager.

Firstly, it allows you to create a separate code block, but most importantly it has a special functionality where some code is run Before or After the code you write.

In case of with open, there there is some code executed in the end to close the file safely, which is a big topic when you read and write files. If you wouldn't close it, it would be corrupt, so therefore it's already included in the with open context manager to make your life easier.

💡Also there is a special class in C# to read and write files.

// Using 'using' with files
using (StreamReader reader = new StreamReader("file.txt"))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content

# Using a context manager with a file
with open('file.txt', 'r') as file:
    data = file.read()
    print(data)

List<T>

Lastly, I want to point your attention to typed list in .NET framework. The biggest difference is that you define the allowed types of elements inside that list and nothing else can be added inside. This ensures that when you provide the list as an argument it already has the right elements.

You will often see IList or ICollection as a requirement in Revit API Docs, and we need to use this list. This List can be used for both IList and ICollection requirement in the docs.

In general you just provide a python list inside of .NET List as an argument and ensure that you use the right Types. And then you won't have any issues.

py_list = [ElementId(12345), ElementId(12346)]
myList = List[ElementId](py_list)

Conclusion

So, that’s it! We’ve covered the basics of Python vs. C# for Revit API development. They’re not as different as they might seem at first—the main logic is the same, and once you get used to the syntax, translating between the two is pretty straightforward.

I hope this makes it easier for you to work with examples from Revit API documentation, even if they’re in C#.

In the next lesson, I’ll show you step by step how to translate C# examples into Python, so you can see it all in action.

HomeWork

✅ Compare syntax examples between C# and Python in this lesson.

👀 We are going to go through Revit API Docs and translate a few C# examples to python in the next Lesson!

💡 Remember, you don't need to learn C# to do that! Just get familiar with it.

⌨️ Happy Coding!

Questions:

Should I learn C#?

Should I learn C#?

What is OOP?

What is OOP?

Discuss the lesson:

P.S. Sometimes this chat might experience connection issues.
Please be patient or join via Discord app so you can get the most out of this community and get access to even more chats.

P.S. Sometimes this chat might experience connection issues.
Please be patient or join via Discord app so you can get the most out of this community and get access to even more chats.

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API