In a recent question on Stack Overflow, I asked how I might parse through a file name to extra meta info about a file.
After I worked through that problem, I decided that I might want to create new type of object to hold the meta data and the original file. I thought I might do something like this:
class BackupFileInfo : FileInfo, IEquatable<BackupFileInfo> { //Properties and Methods here }
The idea would be that I would retain the original FileInfo
object while adding meta information in the properties of the object that implements FileInfo
, such as IsMainBackup
.
However, FileInfo
is sealed, which means other classes cannot inherit from it.
Instead, I ended up with the following:
class BackupFileInfo : IEquatable<BackupFileInfo> { public bool IsMainBackup { get; set; } public int ImageNumber { get; set; } public int IncrementNumber { get; set; } public FileInfo FileInfo { get; set; } //public BackupFileInfo() //constructor here public bool Equals(BackupFileInfo other) { return (this.FileInfo.Name == other.FileInfo.Name && this.FileInfo.Length == other.FileInfo.Length); } }
I'm not terribly excited about this solution because instead of being able to use BackupFileInfo.Length
, I'm going to have to use BackupFileInfo.FileInfo.Length
. Perhaps this is the best practice already, but something doesn't feel right.
Is there a better way to deal with this problem?
A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated. The design intent of a sealed class is to indicate that the class is specialized and there is no need to extend it to provide any additional functionality through inheritance to override its behavior.
You cannot derive or extend any class from it. Sealed method is implemented so that no other class can overthrow it and implement its own method. The main purpose of the sealed class is to withdraw the inheritance attribute from the user so that they can't attain a class from a sealed class.
In C# you use the sealed keyword in order to prevent a class from being inherited. In VB.NET you use the NotInheritable keyword. In Java you use the keyword final .
Sealed classes cannot be instantiated directly. Sealed classes cannot have public constructors (The constructors are private by default). Sealed classes can have subclasses, but they must either be in the same file or nested inside of the sealed class declaration.
This is one of the classic composition instead of inheritance examples and you went in the right direction.
To solve your property problem just create a property called Length
that delegates to the encapsulated FileInfo
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With