Display common values ​​from user structure / type

One of my projects has a / struct value type, which is a user-id string for the video format. In this case, it will contain a string of type content, but this can change.

I used a structure so that it could be heavily printed when it passed, and perform some health checks on the original value of the string.

public struct VideoFormat { private string contentType; public VideoFormat(string contentType) { this.contentType = contentType; } public string ContentType { get { return this.contentType; } } public override string ToString() { return this.contentType; } // various static methods for implicit conversion to/from strings, and comparisons } 

As there are several very common formats, I expanded them as read-only static fields with default values.

 public static readonly VideoFormat Unknown = new VideoFormat(string.Empty); public static readonly VideoFormat JPEG = new VideoFormat("image/jpeg"); public static readonly VideoFormat H264 = new VideoFormat("video/h264"); 

Is it better to set general values ​​as read-only static fields or how to get only properties? what if i want to change them later? I see both methods used within the .Net framework, for example. System.Drawing.Color uses readonly static properties, while System.String has a static read field for String.Empty , and System.Int32 has a constant for MinValue .

(Mostly copied from this question , but with a more specific and not directly related question.)

+4
source share
1 answer

Properties are a good idea if you do not declare something that never changes.

Using properties, you can change the internal implementation without affecting the programs consuming your library, and handle the changes / options. Consuming programs will not be broken and will not need to be recompiled.

eg. (I know this is a bad example, but you get the idea.)

 public static VideoFormat H264Format { get{ // This if statement can be added in the future without breaking other programs. if(SupportsNewerFormat) return VideoFormat.H265; return VideoFormat.H264; } } 

Also keep in mind that if you decide to change the field to a property in the future, consumer code breaks.

+2
source

All Articles