C# Object reference null but not null [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The forum is full of posts about problems like this. I've red some but didn't manage to solve my own problem.
I get Exception error:
Object reference not set to an instance of an object.
try
{
CZaposleni zap = new CZaposleni();
zap.Sifra = "1234567894567";
zap.Ime = "testIme";
zap.Prezime = "testPrezime";
zap.Pol = Char.Parse("M");
zap.JMBG = "1234567899871";
zap.Brknjizice = "12345";
zap.SS = "4.test";
zap.DatumR = DateTime.Parse("4/11/2013");
zap.DatumZ = DateTime.Parse("4/11/2013");
zap.Mestorodj = "testMesto";
zap.Prebivaliste = "testPrebivaliste";
zap.Kontakt1 = "654987";
zap.Kontakt2 = "564845";
CRadnaMesta rad = new CRadnaMesta();
rad.ID = Int32.Parse(cbRadnaMesta.SelectedValue.ToString());
Console.WriteLine("Zap = "+zap.ID +" Rad = "+rad.ID);
zap.Radnomesto = rad;
Console.WriteLine("Zap check 1: " + zap.ID + " " + zap.Radnomesto.ID);
zap.dodajRadnika();
Console.WriteLine("Zap check 2: "+zap.ID+" "+zap.Radnomesto.ID);
}
catch (Exception ex)
{
MessageBox.Show("Frm: "+ex.Message);
}
The code breaks at 'zap.Radnomesto = rm;' since last output when running the code i get is
rm.ID = 1
zap.ID = 0
So none of two objects is null.

I believe your error is in the CZaposleni class in the following code:
public CRadnaMesta Radnomesto
{
get
{
return radnomesto;
}
set
{
if ( radnomesto.ID == 0 )
throw new Exception("Morate uneti radno mesto.");
radnomesto = value;
}
}
More precisely in if ( radnomesto.ID == 0 ). Since radnomesto is null if not set, you're getting the error while checking for the ID.
You should use the following code instead:
public CRadnaMesta Radnomesto
{
get
{
return radnomesto;
}
set
{
if ( value == null || value.ID == 0 )
throw new Exception("Morate uneti radno mesto.");
radnomesto = value;
}
}

Related

Different array value from different function [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I'm still learning about Unity and trying to create some simple games.. but i got a same error for a few days when i tried to fill array from public function.. it said that my index was outside the bounds of array..
is there anything related with public or not?
i do know about the cause of this error. what iam asking is why it gives different value from different function(same script)?
please help :d (sorry for my bad english)
this is my code :
public void PencetTombol()
{
//this is where i got error line
prefab[0].GetComponentInChildren<Text>().text = "test";
}
void cekkata()
{
//this code works
prefab[0].GetComponentInChildren<Text>().text = "test";
}
void buat_kotak()
{
pindah = false;
var test = "CHELSEA";
prefab = new GameObject[test.Length];
for (int i = 0; i < test.Length; i++)
{
if (test[i] != ' ')
{
prefab[i] = Instantiate(prefab2, new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity);
if (pindah == false)
{
prefab[i].transform.SetParent(panelatas.transform, false);
}
else
{
prefab[i].transform.SetParent(paneltengah.transform, false);
}
}
else
{
pindah = true;
}
}
}
Your error has no connection with access modifiers.
This error is thrown when you try to access an array element that does not yet exist.
Example:
string[] test = { "test" };
var x = test[0]; --> success
var y = test[1]; --> out of bounds

remove loop in linq cause slow the performance [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
want to remove foreach loop and done with Linq....Please suggest
In ViewModal I have LeadStatus Name and in LeadModal i have Id of LeadStatus on basis of Id I have to fatch Name from LeadStatusTable and bind in ViewModal
Thanks
List<Entities.LeadViewModel> leadViewModels = new List<Entities.LeadViewModel>();
IEnumerable<Entities.Lead> leads = await _leadRepository.AllNonDeletedAndConvertedLeads();
foreach (var lead in leads)
{
Entities.ChetuUser chetuUser = await _chetuUserRepository.GetChetuUser(lead.OwnerId);
if (!string.IsNullOrEmpty(lead.Status))
{
LeadStatusMaster leadStatusMaster = await _masterTableRepository.LeadStatusMasterById(lead.Status);
if (chetuUser != null && leadStatusMaster != null)
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = leadStatusMaster.Name,
CreatedDate = lead.CreatedDate
});
}
else if (chetuUser != null && leadStatusMaster == null)
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = "",
CreatedDate = lead.CreatedDate
});
}
else
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = "",
CreatedDate = lead.CreatedDate,
OwnerName = ""
});
}
}
else
{
if (chetuUser != null)
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = "",
CreatedDate = lead.CreatedDate,
OwnerName = chetuUser.EmployeeName
});
}
}
}
return leadViewModels;
Your title is different by the asked question. Because you speak about the speed replaceing the foreach with linq will not speed up your loop. The problem is the awaits in it. Moreover the linq's foreach is a little tricky to work with await:
C# async await using LINQ ForEach()

What to return if condition is not satisifed? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The method looks as following:
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
var result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
return result;
}
}
It's obvious that not all paths return something and the issue is I can't return null.
How to rearrange the method?
Maybe you can initialize your List?
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
List<string> result = new List<string>()
{
owner,
string.Empty,
string.Empty
};
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
}
return result;
}
I usually do this when I want to create an assembler method for example to tranform a List<X> to another List<Y>, so if my List<X> is null I try to return an empty List of Y. I prefer to do this instead of throwing exceptions and getting my Dashboard full of errors. But It depends on how your codes works.

Generic extension method for retrieving 'default' value?

I'm playing around a bit with determining the default values of objects, based on the example here:
https://stackoverflow.com/a/3195792/1293496
This particular extension method was created for System.Type. What I was trying to accomplish was to make this even more generic, where I could do something like this:
int i = 3;
bool amIaDefaultValue = i.IsDefaultValue();
I would expect this to return true if i == 0 (the default value for an int), and false for all other instances.
Here is my initial attempt:
public static bool IsDefaultValue<T>(this T value)
{
var t = typeof(T); // always comes back as object..?
if (t.IsValueType && Nullable.GetUnderlyingType(t) == null)
{
return value.Equals(Activator.CreateInstance<T>());
}
else
{
var defaultValue = default(T);
if (value == null)
return defaultValue == null;
else
return value.Equals(defaultValue);
}
}
On the plus side, I'm able to attach .IsDefaultValue() to any object. Unfortunately, the type of T always comes back as System.Object. I can get the correct type if I set it up this way:
var t = typeof(value);
But if the value happens to be null, I'll get an error straight away. Is there a good workaround for implementing an extension method like this? Or should I stick to the tried and tested route from the example?
Edit
As pointed out by comments, it seems I oversimplified this a bit and missed the root of the problem. Here's what was actually calling my IsDefaultValue():
foreach (var imprintProperty in deltas.GetType().GetProperties())
{
var value = imprintProperty.GetValue(deltas);
if (!value.IsDefaultValue())
{
// get corresponding prop in programmable area
var programmableProp = progarea.GetType().GetProperty(imprintProperty.Name);
if (programmableProp != null)
programmableProp.SetValue(progarea, value);
}
}
And now it becomes obvious that .GetValue is always returning as System.Object. Uff.
Is it still possible to treat the object as its underlying type in the extension method? Sorry for the confusion with this.
Take a look at this:
static class Program
{
static void Main()
{
int a = 1;
Console.WriteLine("a.IsDefaultValue() : " + a.IsDefaultValue());
a = 0;
Console.WriteLine("a.IsDefaultValue() : " + a.IsDefaultValue());
object obj = new object();
Console.WriteLine("obj.IsDefaultValue() : " + obj.IsDefaultValue());
obj = null;
Console.WriteLine("obj.IsDefaultValue() : " + obj.IsDefaultValue());
int? b = 1;
Console.WriteLine("b.IsDefaultValue() : " + b.IsDefaultValue());
b = null;
Console.WriteLine("b.IsDefaultValue() : " + b.IsDefaultValue());
Console.ReadKey(true);
}
static bool IsDefaultValue<T>(this T value)
{
if (ReferenceEquals(value, null))
{
return true;
}
var t = value.GetType();
if (t.IsValueType)
{
return value.Equals(Activator.CreateInstance(value.GetType()));
}
return false;
}
}
Apparently works (I've to say that I was convinced that the other way should have worked but not)

Word.Shape.Name taking maximum 18 characters

I am using Word.Interop library. If I assign less than 18 characters to 'Word.Shape.Name' then it work perfect but when I assign more than 18 characters then 'Word.Shape.Name' throw exception.
e.g
Word.Shape.Name = "This is a test value to assign";
throw exception
"System.UnauthorizedAccessException: Access is denied.
(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))".
What I should do to resolve this problem?
Whole method is
objTargetDocument, ref Scripting.Dictionary dicMarkers, ref Alias.Document objSourceDocument)
{
bool blnRetVal = false;
string strModel = ndModel.Name;
int lngModel = 0;
int lngNextModel = 0;
int lngStart;
int lngEnd;
Alias.Document objTemp;
Microsoft.Office.Interop.Word.Range objRange;
Shape objShape;
Object[] astr;
int n;
bool bLastModel;
/*'--------------------------------------------------------------------------------------------------
' 1. Find model's model marker and the next marker (if any)
'--------------------------------------------------------------------------------------------------*/
astr = dicMarkers.Keys();
for (n = astr.GetLowerBound(0); n <= astr.GetUpperBound(0); n++)
{
if (string.Compare(astr[n].ToString(), strModel, true) == 0)
{
lngModel = (int)dicMarkers.get_Item(astr[n]); //PNDC //dicMarkers.Item(astr(n))
if (n < astr.GetUpperBound(0))
{
if (string.Compare(astr[n + 1].ToString(), "#end", true) == 0)
{
lngNextModel = 0;
bLastModel = true;
}
else
{
lngNextModel = (int)dicMarkers.get_Item(astr[n + 1]);
bLastModel = false;
}
}
else
{
lngNextModel = 0;
}
break;
}
}
/*'--------------------------------------------------------------------------------------------------
' 2. Copy model from original document to new document
'--------------------------------------------------------------------------------------------------*/
if (lngModel > 0)
{
lngStart = objSourceDocument.Sections[lngModel].Range.Start;
if (lngNextModel == 0)
{
var key = "#end";
var value = dicMarkers.get_Item(key);
lngEnd = value;
}
else
lngEnd = objSourceDocument.Sections[lngNextModel].Range.Start; //objSourceDocument.Sections.Last.Index;
//--------------------------------------------------------------------------------------------------
//copy original
objSourceDocument.ActiveWindow.Selection.SetRange(lngStart, lngEnd);
objSourceDocument.ActiveWindow.Selection.Copy();
bool bInsertSection = false;
//paste (append) copied model to the document
if (objTargetDocument.Sections.First.Index == objTargetDocument.Sections.Last.Index)
{
//Target document only has 1 (default) section
bInsertSection = true;
}
else
{
if (objTargetDocument.Sections.Last.PageSetup.SectionStart == WdSectionStart.wdSectionNewPage)
{
//Last section is a nextpage section
if ((objTargetDocument.Sections.Last.Range.End - (objTargetDocument.Sections.Last.Range.Start) <= 1))
//Empty section
bInsertSection = false;
else
bInsertSection = true;
}
else
{
//Last section isn't a nextpage
bInsertSection = true;
}
}
objTargetDocument.ActiveWindow.Selection.Start = objTargetDocument.Range().End;
if (bInsertSection)
{
objTargetDocument.ActiveWindow.Selection.InsertBreak(WdBreakType.wdSectionBreakNextPage);
objTargetDocument.ActiveWindow.Selection.Start = objTargetDocument.Range().End;
}
objTargetDocument.ActiveWindow.Selection.Collapse();
objRange = objTargetDocument.ActiveWindow.Selection.Range.Duplicate; //remember range for model marker anchor
objTargetDocument.ActiveWindow.Selection.Paste();
objTargetDocument.Variables.Add(m_strModelMarker + strModel);
// .TextFrame.ContainingRange
//place model marker (so that we can find our model again)
objShape = objTargetDocument.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationUpward, 0, 0, 0, 0, objRange);
objShape.Name = m_strModelMarker + strModel; // This Line Trowing Exception
objShape.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
UpdateFields(ref objTargetDocument, ref ndModel);
blnRetVal = true;
}
else
new Modules.Globals().MsgBoxEx("Kan het bestaande model '" + strModel + "' niet kopieren.", MessageBoxButtons.OK);
return blnRetVal;
}
I haven't been able to find any reference to a 18-character limitation in the Name property. Also, after a quick test, it seems to work fine (even by inputting a much longer length):
Word.Shape oShape = oDoc.Shapes.AddLine(0, 0, 0, 0);
oShape.Name = "This is a test value to assign - This is a test value to assign";
Thus, the error you are mentioning is most likely provoked by a different part of your code.
In any case, I am not sure that you understand the exact meaning of the Name property. This is not something you would be seeing in the Word document at all; this is something for "internal reference purposes". The Shapes array is actually a Dictionary which can be accessed by typing either the index or the name of the given shape; that is, if oShape, as defined above, is the first shape in the document, I can access it by using any of the folowing options:
Word.Shape oShape2 = oDoc.Shapes[1];
Word.Shape oShape2 = oDoc.Shapes["This is a test value to assign - This is a test value to assign"];
For this reason, writing too long names is not necessary anyway.
There is an old discussion here about Word 2003 which seems to be similar.
In that discussion, it suggests storing the name in a document variable object (as in Document.Variables).
Something like:
Variables vars = Doc.Variables;
var = vars.Add("myShapeName", "This is a test value to assign");
and then assign var.Value to Word.Shape.Name somehow.
Edit
On re-reading that linked discussion, there is no way of directly assigning a Doc.Variable to the Name property. What you can set the shape's Name to a short unique identifier and use it to retrieve your long string from the Variables wherever you need it.
void SetLongName(Shape shape, string uniqueId, string longName)
{
shape.Name = uniqueId;
Variables vars = Doc.Variables;
var = vars.Add(uniqueId, longName);
}
string GetLongNameOfShape(Shape shape)
{
return GetLongNameById(shape.Name);
}
string GetLongNameById(string uniqueId)
{
Variables vars = Doc.Variables;
return vars.get_Item(uniqueId).Value;
}

Categories