I'm reviewing someone's code and came across this private class:
class CustomType : Dictionary<int, SomeOtherCustomType> { // This is empty; nothing omitted here }
CustomType is then used all over the parent class. This is neat of course, since CustomType is shorter than
Dictionary<int, SomeOtherCustomType>
My question is, what are the performance/memory implications of having an inner class just for a shortcut? In a performance sensitive application, does this contribute (even slightly) to higher memory and/or CPU usage?
Private class fields are designed to be inaccessible from the outside. There is a way to overcome this. You can create new method and return the private class field from that method. You can define this method either as public method or static. Just like with static properties, you can call static methods without instantiating the class.
The syntax for private methods is the same as for private class fields. The name of the method has to always start with the # symbol. class MyClass { // Declare private class field #myPrivateField = 'I am private.'
This is where private methods and class fields can be handy. The idea of keeping some things private is simple and straightforward. When you want to keep something private, be it a property or method, it should be accessible only from one place. This place is the class in which you defined that property or method.
When you want to declare class field as static, you have to start with the static keyword. This keyword is then followed by the class field name. In case of private class field, the name is prefixed by the # symbol. // Alternative with static method class MyClass { // Declare private class field as static static #myPrivateField = 'I am private.'
Unless there's another reason for defining a custom type I'd suggest changing it to a using statement.
using CustomType = Dictionary<int, SomeOtherCustomType>;
It just defines an alias for the dictionary and can be quite useful if you're consuming some complicated parameterised classes.
This eliminates the need of declaring a new type, because as the code stands at the moment the following would fail.
CustomType dictionary = new Dictionary<int, SomeOtherCustomType>(); //custom type is a different class and can't be instantiated with a dictionary
However, it would work if you use an alias instead.
The short and the long of it is, no. The class CustomType
is by definition a Dictionary<int, SomeOtherCustomType>
and so it will be allocated as such.
This is particularly true because there literally is no implementation for the class.
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