Version class in C#

gpeipman
11.3K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Version class

There is built-in Version class available in .NET and it is easy to use in C#. Version class supports major, minor, build and revision numbers as integers. Class cam be initialized from string or with some combination of versions. Here are class constructors.

public Version(string version);
public Version(int major, int minor);
public Version(int major, int minor, int build);
public Version(int major, int minor, int build, int revision);

Initialization from version number parts is self describing. Let's see how to initialize version from string.

Now let's try out how intelligent Version class is and let's expect that missing version parts in version string are considered as zeros.

But what if we give only major version?

This is the situation that Version class cannot handle. There must be major and minor versions. Minor version can be zero but it must be given when version is parsed from string.

Using Version class in code

Now let's see how to use Version class in real code. Often we cannot make application throw exceptions to user when we can avoid it and clearly communicate the problem to user.

If we have more logic needed or we want to keep application architecture clean then we can also create Version factory.

We can add more logic to VersionFactory class if needed.

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content