Search code examples
c#classlanguage-featuresinstancereadonly

How to instance classes with readonly attributes


I want to create an instance of the AudioFormat class from all the required information.

Basically, what I have is

  • int BitsPerSample
  • int Channels
  • int SamplesPerSecond
  • WaveFormatType WaveFormat

The problem is, that simply using something like

AudioFormat format = new AudioFormat();
format.BitsPerSample = BitsPerSample;
[...]

doesn't work, since Property or indexer 'System.Windows.Media.AudioFormat.BitsPerSample' cannot be assigned to -- it is read only.

Is there an easy way to create such an object? If not, what should I do to create it? Using inheritance, overriding the properties so that they have setters? Creating an XML representation of the object and then deserialize it? Using some other ugly hacks (no unsafe :-) )?


Solution

  • You are not supposed to create this class directly.
    It exists to return information from the AudioCaptureDevice class, from the SupportedFormats property, using an internal constructor.

    If you're trying to use it for your own purposes, you should create your own class.