Search code examples
pythonc#namedtuple

Converting Python tuple to C#


I am in the process of converting a program from Python to C#. I'm about 80% there, but I came across this code in Python and I am not sure exactly how this would translate over to C#:

from typing import NamedTuple

class Mode(NamedTuple):
    inh: int = None
    inh_sz: int = 0
    imm: int = None
    imm_sz: int = 0
    dir: int = None
    dir_sz: int = 0
    ind: int = None
    ind_sz: int = 0
    ext: int = None
    ext_sz: int = 0
    rel: int = None
    rel_sz: int = 0

It appears to be a class that inherits from the Python NamedTuple class. Any guidance on how this would translate over to C# would be appreciated.


Solution

  • Although you can use tuples in C# 7.0 or later, the more traditional way of writing a class like Mode in C# is to just use a normal class with a property for each “tuple” item.

    If it's important that you be able to access a Mode object's properties by index or by name, as you can with Python's named tuples, then you can add an indexer to the class.