Here is my example: I want to know if it is possible to pass an argument initialized with null, and later initialize the object with a correct value.  private class Source {   String str;   String getStringValue() {     return str;   }   void setStringValue(String str) {     this.str = str;   } }  private class UserSource {   Source src;   UserSource(Source src) {     this.src = src;   }   String getValue() {     return src.getStringValue();   }   void setValue(String str) {     src.setStringValue(str);   } }   Now how I'm using.    Source srcW = new Source();   UserSource userSourceW = new UserSource(srcW);   srcW.setStringValue("Second Value");   System.out.println("From UserSource:" + userSourceW.getValue());   userSourceW.setValue("Is not Second");   System.out.println("From Source:" + srcW.getStringValue());   The output:  From UserSource:Second Value From Source:Is not Second   But,  want to know if is possible to use like:    Source srcN = null;  // YES I want to assign Not initialized!   UserSource userSourceN = new UserSource(srcN);   srcN = new Source();   srcN.setStringValue("First Value");   System.out.println("From UserSource:" + userSourceN.getValue());   Of course the output is  Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException   Is there an alternative?
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
3286
Does the order in which I set properties using the object initializer syntax get executed in the exact same order?  For instance if I do this:  var s = new Person { FirstName = "Micah",                      LastName = "Martin",                      IsLoaded = true                    }   will each property get set in the same order?
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.
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
112799
In JavaScript, there are two values which basically say 'I don't exist' - undefined and null.  A property to which a programmer has not assigned anything will be undefined, but in order for a property to become null, null must be explicitly assigned to it.  I once thought that there was a need for null because undefined is a primitive value and null an object. It's not, even if typeof null will yield 'object': Actually, both are primitive values - which means neither undefined nor null can be returned from a constructor function, as both will be converted to an empty object (one has to throw an error to proclaim failure in constructors).  They also both evaluate to false in boolean contexts. The only real difference I can think of is that one evaluates to NaN, the other to 0 in numeric contexts.  So why is there both undefined and null if this just confuses programmers who are incorrectly checking for null when trying to find out whether a property has been set or not?  What I'd like to know is if anyone has a reasonable example where it's necessary to use null which couldn't be expressed using undefined instead.  So the general consensus seems to be that undefined means 'there is no such property' while null means 'the property does exist, but holds no value'.  I could live with that if JavaScript implementations would actually enforce this behavior - but undefined is a perfectly valid primitive value, so it can easily be assigned to existing properties to break this contract. Therefore, if you want to make sure if a property exists, you have to use the in operator or hasOwnProperty() anyway. So once again: what's the practical use for separate values for undefined and null?  I actually use undefined when I want to unset the values of properties no longer in use but which I don't want to delete. Should I use null instead?
103793
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:  T createDefault() {     if(typeof(T).IsValueType)     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:  T createDefault() {     if(typeof(T).IsValueType || typeof(T).FullName == "System.String")     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   But this feels like a kludge. Is there a nicer way to handle the string case?
89434
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:  public void test1() {     // Throw an exception for testing purposes     throw new ArgumentException("test1"); }  void test2() {     try     {         MethodInfo mi = typeof(Program).GetMethod("test1");         mi.Invoke(this, null);     }     catch (TargetInvocationException tiex)     {         // Throw the new exception         throw tiex.InnerException;     } }
35959
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.  Should I do it at declaration?:  public class Dice {     private int topFace = 1;     private Random myRand = new Random();      public void Roll()     {        // ......     } }   or in a constructor?:  public class Dice {     private int topFace;     private Random myRand;      public Dice()     {         topFace = 1;         myRand = new Random();     }      public void Roll()     {         // .....     } }   I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.
58615
Have you ever tried this before?  static void Main(string[] args) {     int x = 10;     x = x++;     Console.WriteLine(x); }   Output: 10.  but for   static void Main(string[] args) {     int x = 10;     x++;     Console.WriteLine(x); }   Output: 11.  Could anyone explain why this?
38112
Here's the scenario...    if (entry.Properties["something"].Value != null)   attribs.something = entry.Properties["something"].Value.ToString();   While effective and working correctly, this looks ugly to me.  If I don't check for a null before performing the ToString() then it throws an exception if the property was null.  Is there a better way to handle this scenario?  Much appreciated!
30627
In C# the Main class has string[] args parameter.  What is that for and where does it get used?
119860
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be &quot;reset&quot; on each iteration. Could someone explain why they would not be)? (My first question, really looking forward to the responses.) The example below is obviously not the code in question but reflects the scenario:  Please excuse the code example, it looks fine in the editor preview?? for (int i =0; i&lt; 10; i++) {     decimal? testDecimal;     string testString;      switch( i % 2  )     {         case 0:         testDecimal = i / ( decimal ).32;         testString = i.ToString();             break;         default:             testDecimal = null;             testString = null;             break;     }      Console.WriteLine( &quot;Loop {0}: testDecimal={1} - testString={2}&quot;, i, testDecimal , testString ); }   EDIT: Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some &quot;case&quot;'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop. Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that &quot;obviously the variables would not be reinitialized on each loop&quot;? A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out &quot;the value is never used&quot; and removed them.  EDIT: Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a &quot;Code Cleanup&quot; on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show &quot;all green&quot; so &quot;moved his variables closer to assignment&quot; then &quot;Removed redundant assignment&quot;! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed! How to do mark a question as answered?
91640
I have a model class:  class Person(db.Model):   first_name = db.StringProperty(required=True)   last_name = db.StringProperty(required=True)   I have an instance of this class in p, and string s contains the value 'first_name'. I would like to do something like:  print p[s]   and   p[s] = new_value   Both of which result in a TypeError.  Does anybody know how I can achieve what I would like?
17824
I had one batch class in which i am passing some data required for creating object record.But when i call that batch class from parent class variables are initialized but start method are not called as there is no record to query i also tried with iterable object but not able to do that.My code is as below  global class testBatchClass implements Database.Batchable&lt;SObject&gt;,Database.Stateful{     public List&lt;sObject&gt; sObjectList;     public string objectName;     public String dataList;      public testBatchClass(String objectName,String inputdata){          String listType = 'List&lt;'+objectName+'&gt;';         system.debug('list type value is'+listType);         List&lt;SObject&gt; castRecords = (List&lt;SObject&gt;)Type.forName(listType).newInstance();         this.sObjectList = castRecords;         this.objectName = objectName;         this.dataList = inputdata;      }     global Iterable&lt;SObject&gt; start(Database.BatchableContext batchableContext) {         return new sObjectList{};     }     global void execute(Database.BatchableContext batchableContext, List&lt;sobject&gt; scope){          List&lt;OpportunityRenewal__mdt&gt; mdtList = new List&lt;OpportunityRenewal__mdt&gt;([Select id,Api_Name_of_Fields__c,Sobject_Name__c from TestFileUploadCustomSetting1__mdt where Sobject_Name__c=:objectName]);         List&lt;String&gt; fieldName = new List&lt;String&gt;();         for(OpportunityRenewal__mdt md : mdtList){             if(md.Sobject_Name__c == objectName){                 fieldName = md.Api_Name_of_Fields__c.Split(',');                 break;             }         }         List&lt;String&gt; dataRowsSplit= dataList.split(',');         dataRowsSplit.remove(0);         for(String eachRow: dataRowsSplit){             List&lt;String&gt; splitString = eachRow.Split(',');             sObject sobj = Schema.getGlobalDescribe().get(objectName).newSObject();             for(Integer i=0; i &lt;= splitString.Size(); i++){                 sobj.put(fieldName[i],splitString[i]);             }             scope.add(sobj);         }         if(scope != Null &amp;&amp; scope.Size() &gt; 0){             upsert scope;         }     }      global void finish(Database.BatchableContext batchableContext) {} }   Thanks
37105
I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I:  return null throw an exception other  Which is the best practise or idiom?
76867
Should you set all the objects to null (Nothing in VB.NET) once you have finished with them?   I understand that in .NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part?  I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).  So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?  MSDN articles never do this in examples and currently I do this as I cannot  see the harm. However I have come across a mixture of opinions so any comments are useful.
56271
C#6 Update  In :  // C#1-5 propertyValue1 = myObject != null ? myObject.StringProperty : null;   // C#6 propertyValue1 = myObject?.StringProperty;   The question below still applies to older versions, but if developing a new application using the new ?. operator is far better practice.  Original Question:  I regularly want to access properties on possibly null objects:  string propertyValue1 = null; if( myObject1 != null )     propertyValue1 = myObject1.StringProperty;  int propertyValue2 = 0; if( myObject2 != null )     propertyValue2 = myObject2.IntProperty;   And so on...  I use this so often that I have a snippet for it.  You can shorten this to some extent with an inline if:  propertyValue1 = myObject != null ? myObject.StringProperty : null;   However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:  propertyValue1 = myObject != null ?      (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;   What I really want is ?? style syntax, which works great for directly null types:  int? i = SomeFunctionWhichMightReturnNull(); propertyValue2 = i ?? 0;   So I came up with the following:  public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action, TResult valueIfNull )     where T : class {     if ( input != null ) return action( input );     else return valueIfNull; }  //lets us have a null default if the type is nullable public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action )     where T : class     where TResult : class { return input.IfNotNull( action, null ); }   This lets me us this syntax:  propertyValue1 = myObject1.IfNotNull( x =&gt; x.StringProperty ); propertyValue2 = myObject2.IfNotNull( x =&gt; x.IntProperty, 0);  //or one with multiple levels propertyValue1 = myObject.IfNotNull(      o =&gt; o.ObjectProp.IfNotNull( p =&gt; p.StringProperty ) );   This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.  This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:  if( ( obj1 == null &amp;&amp; obj2 == null ) ||      ( obj1 != null &amp;&amp; obj2 != null &amp;&amp; obj1.Property == obj2.Property ) )     ...  //becomes if( obj1.NullCompare( obj2, (x,y) =&gt; x.Property == y.Property )      ...   What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?    I guess what I really want here is a compiler/language extension:  propertyValue1 = myObject != null ? myObject.StringProperty : null;  //becomes propertyValue1 = myObject?StringProperty;   This would make the complex case far easier:  propertyValue1 = myObject != null ?      (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null  //becomes propertyValue1 = myObject?ObjectProp?StringProperty;   This would only work for value types, but you could return nullable equivalents:  int? propertyValue2 = myObject?ObjectProp?IntProperty;  //or  int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;