I've looked and didn't quite find similar to what I'm dealing with.  Hopefully a solution, or offer for better implementation.  I have a class that may be passed with an optional parameter that is preserved to the instance created.  I then have a derived class with similar optional parameter, but in its non-parameter constructor does other preparation stuff regardless of the optional parameter.  What would be the correct way to have it call the base-class parameter constructor, yet still do the non-parameter constructor of the derived.  public class MyBaseClass {    protected object preserveParm;    protected int someValue;     public MyBaseClass()    {       someValue = 1;    }     public MyBaseClass( object SomeParm ) : this()    {       preserveParm = SomeParm;    } }  public class DerivedClass : MyBaseClass {    private int customSecondaryProp;    private DateTime when;     public DerivedClass()    {       customSecondaryProp = 10;       someValue = 5;    }     public DerivedClass( object SomeParm ) : base( SomeParm )    {       when = DateTime.Now;    } }   So, if I do a   DerivedClass test = new DerivedClass( "testing" );   I need it to hit the base class to preserve the parameter, yet ALSO hit the derived class's non-parameter to set the sample bogus values.  As it stands now, the Derived parameter method is hit, which then hits the base class's parameter constructor which calls the "this()" of the base class, and returns up the chain to the DerivedClass parameter constructor, finishes itself, but never hits the DerivedClass constructor.  Is there a way to force both the baseclass parameterless AND the DerivedClass parameterless constructor?
121961
I have two classes, Foo and Bar, that have constructors like this:  class Foo {     Foo()     {       // do some stuff     }      Foo(int arg)     {       // do some other stuff     } }  class Bar : Foo {     Bar() : base()     {       // some third thing     } }   Now I want to introduce a constructor for Bar that takes an int, but I want the stuff that happens in Bar() to run as well as the stuff from Foo(int).  Something like this:  Bar(int arg) : Bar(), base(arg) {   // some fourth thing }   Is there any way to do this in C#?  The best I have so far is putting the work done by Bar() into a function, that also gets called by Bar(int), but this is pretty inelegant.
98970
I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.  public class SomeBaseClass {     public string GetBaseClassName {get;set;}     public bool BooleanEvaluator {get;set;} }  public class SomeDerivedClass : SomeBaseClass {     public void Insert(SqlConnection connection) {           //...random connection stuff           cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar;           //...     } }  public static void Main(object[] args) {     SomeBaseClass baseClass = new SomeBaseClass();     SomeDerivedClass derClass = (SomeDerivedClass)baseClass;      derClass.Insert(new sqlConnection()); }   I know this seems goofy but is there any way to accomplish something of this sort?
13449
I can't understand where the final keyword is really handy when it is used on method parameters.    If we exclude the usage of anonymous classes, readability and intent declaration then it seems almost worthless to me.   Enforcing that some data remains constant is not as strong as it seems.    If the parameter is a primitive then it will have no effect since the parameter is passed to the method as a value and changing it will have no effect outside the scope.  If we are passing a parameter by reference, then the reference itself is a local variable and if the reference is changed from within the method, that would not have any effect from outside of the method scope.    Consider the simple test example below. This test passes although the method changed the value of the reference given to it, it has no effect.  public void testNullify() {     Collection&lt;Integer&gt; c  = new ArrayList&lt;Integer&gt;();           nullify(c);     assertNotNull(c);            final Collection&lt;Integer&gt; c1 = c;     assertTrue(c1.equals(c));     change(c);     assertTrue(c1.equals(c)); }  private void change(Collection&lt;Integer&gt; c) {     c = new ArrayList&lt;Integer&gt;(); }  public void nullify(Collection&lt;?&gt; t) {     t = null; }
23872
I have a custom type that I created, which should be persisted in a database (in this case, SQL server) as a guid (though this question is just as valid for an object that could be stored as a string, integer, etc).   When I pass this type as a parameter to a DbCommand object, I get an exception:     ArgumentException: No mapping exists from object type [...] to a known managed provider native type.   I have CType operators on the class that allow implicit conversion to a string, or a guid, but .NET doesn't use these since it doesn't know it should convert the type.  Is there a way to add a type to the internal mapping, or otherwise tell .NET how to store my custom type in the database?  I obviously can convert the type myself when passing it to the .NET stuff, but I'd like this to happen automatically, like it does for most of the built-in types.    I've tried to implement a TypeConverter class for my type (inherits from TypeConverter, overrides CanConvertFrom, CanConvertTo, ConvertFrom, ConvertTo, IsValid, and added the System.ComponentModel.TypeConverter attribute to my class), but this still doesn't work.   I'm assuming it's missing a piece telling .NET what type to convert to when storing the value in the database.     My workaround for this, for now, is that I intercept the list of parameters, before I pass them to SQL server, and have a method that changes my custom type into a guid. This is dirty, but it does work for now, but I still think this question is unanswered.
93253
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.  Example:  public class MyGenericClass&lt;T&gt; {   public void doSomething() {     // Snip...     // Call to a 3rd party lib     T bean = (T)someObject.create(T.class);     // Snip...   } }   Clearly the example above doesn't work  and results in the following error: Illegal class literal for the type parameter T.  My question is: does someone know a good alternative or workaround for this?
40477
In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?  class BaseClass {     public BaseClass()     {         // ... some code     } } class MyClass : BaseClass {     public MyClass() // Do I need to put ": base()" here or is it implied?     {         // ... some code     } }
32530
I was watching , and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?  For example something like the FileStream class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr and the ones from a SafeFileHandle.  FileStream(string,FileMode); FileStream(string,FileMode,FileAccess); FileStream(string,FileMode,FileAccess,FileShare); FileStream(string,FileMode,FileAccess,FileShare,int); FileStream(string,FileMode,FileAccess,FileShare,int,bool);   It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].  What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?
102136
Is there a way to Invoke an overloaded method using reflection in .NET (2.0).  I have an application that dynamically instantiates classes that have been derived from a common base class.  For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without.  I need to call the parameterless method via the Invoke method.  Right now, all I get is an error telling me that I'm trying to call an ambiguous method.  Yes, I could just cast the object as an instance of my base class and call the method I need.  Eventually that will happen, but right now, internal complications will not allow it.  Any help would be great!  Thanks.
31086
I have a generic method defined like this:  public void MyMethod&lt;T&gt;(T myArgument)   The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:  if (myArgument == default(T))   But this doesn't compile because I haven't guaranteed that T will implement the == operator.  So I switched the code to this:  if (myArgument.Equals(default(T)))   Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for.  I can add an explicit null check like this:  if (myArgument == null || myArgument.Equals(default(T)))   Now this feels redundant to me.  ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started.  Is there a better way to solve this problem?  I need to support both references types and value types.
12234
I am wriiting a extension on Case object. There I want to write a save method with my own logic and  want this save method should override the standard Save method.  So my code goes like below:  public class MyCaseControllerExt {      private final Case caseObj;      // get Case record from the standard controller and putting it in a member variable     public MyCaseControllerExt (ApexPages.StandardController stdController) {         this.caseObj = (Case)stdController.getRecord();     }      public override PageReference save(){         // TO DO         return null;      }  }   But, while saving the class, I am getting 1 error :     Save error: MyCaseControllerExt : Method does not override an ancestor   method: System.PageReference save()   So my question is how we will override the existing Save method in extension class?
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
105546
When modelling classes, what is the preferred way of initializing:   Constructors, or Factory Methods   And what would be the considerations for using either of them?  In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)  Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.  In contrast to this I can have a static factory method on those classes which will return null if the record is not found.  Which approach is better in this case, constructor or factory method?
79010
Take the following class as an example:  class Sometype {     int someValue;      public Sometype(int someValue)     {         this.someValue = someValue;     } }   I then want to create an instance of this type using reflection:  Type t = typeof(Sometype); object o = Activator.CreateInstance(t);   Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
19919
I ran into an interesting behavior recently.  It seems that if I override .equals() to take a parameter other than Object, it doesn't get called.  Can anyone explain to me why this is happening?  It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.  Here's much simpler code that shows what I'm seeing:  public class MyClass {   private int x;   public MyClass(int n) { x = n; }   public boolean equals(Object o) { return false; }   public boolean equals(MyClass mc) { return x == mc.x; }   public static void main(String[] args) {     List&lt;MyClass&gt; list = new ArrayList&lt;MyClass&gt;();     list.add(new MyClass(3));     System.out.println("Contains 3? " + list.contains(new MyClass(3)));   } }   When this is run, it prints "Contains 3? false".  It looks like the equals(Object) function is called, even though there is another that would work.  By contrast, if I write equals like this the code works as expected:  public boolean equals(Object o) {   if(!(o instanceof MyClass))     return false;   MyClass mc = (MyClass)o;   return x == mc.x; }   Why isn't it figuring out which version of the function to call based on the type of the parameter?
1947
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?  Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod&lt;T&gt;() using the Type stored in the myType variable?  public class Sample {     public void Example(string typeName)     {         Type myType = FindType(typeName);          // What goes here to call GenericMethod&lt;T&gt;()?         GenericMethod&lt;myType&gt;(); // This doesn't work          // What changes to call StaticMethod&lt;T&gt;()?         Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work     }      public void GenericMethod&lt;T&gt;()     {         // ...     }      public static void StaticMethod&lt;T&gt;()     {         //...     } }
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
24344
What are the C++ rules for calling the base class constructor from a derived class? For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).