setting variable in if statement, then told it's unassigned - c#

I want to initialize an array--I don't know how big it will be. then set it in a condition
so I've got:
string[] my_string;
if(x==2)
{
my_string=File.ReadAllLines("file.txt");
}
string new_string=my_string[1];
It's telling me I've an unassigned local variable, because it's in the condition. How do I get around this?

You need to make sure it has a value if x isn't 2.

At the moment, if x is not equal to 2, then you have no values in your array, but you're still calling that array anyway. One thing you could do is move the new_string assingment inside the if statement. Of course, this may not be the best method if you have other values of x you watch to check against. If so, a Switch..Case might be better.
string[] my_string;
//set new_string to be empty for now
string new_string = String.Empty;
if(x==2)
{
my_string=File.ReadAllLines("file.txt");
//Make sure there are at least two elements
if(my_string.Length >= 2)
//Get the second element of the array (remember, 0 is the first element)
new_string = my_string[1];
}

Why not Create a List instead and then utilize the File.ReadAllLines("file.txt")
also are you including the FilePath along with file.txt
here is a free code snippet for you to use I use this alot when I want to load a TextFile into a List as one bulk load...
List<string> lstLinesFromFile = new List<string>(File.ReadAllLines(yourFilePath+ "file.txt"));
from there you can check in the debugger or add a quickwatch to lstLinesFromFile and see all the text that was loaded. each line from there will be accessed link ordinal so use a for loop or foreach loop

Related

String Splitting another string

I have used Splits in the past, but this one is a bit different for some reason, and I am not sure why...
Code:
string responceuptime = scripting.ReadUntilPrompt();
string[] suptime = responceuptime.Split('s');
UpTime.Text = suptime;
Error:
cannot implicitly convert type string[] to string
That is very basic thing and is very easy to figure out from the error message what is wrong actually.
The following line is the culprit by the way here:
UpTime.Text = suptime;
As suptime is of type string[] which is array while Text property is of type String. When assigning references to and from the type should be same otherwise we will see this error message which you just facing.
It's unclear from the above lines of code that what you are trying to achieve here, but you would need to assign single String object to Text, you cannot assign array or collection to single String object.
Hope it helps.
Your variable suptime is a string[] - an array of strings. While I don't know what Uptime.Text is, I'm guessing that it's looking for a single string, and that's why you're getting the compiler error that you are.
If you want to get the first string out of the array, then you could set it like so:
UpTime.Text = suptime[0];
The output of a call to String.Split is an array of strings (String[]). What your code does, here, is attempting to assign a String[] to a String variable, therefore the application is throwing an exception.
Hence, you must identify, within your array, the value you are looking for and picking the index that points to it (from 0 to suptime.Length - 1). For example:
UpTime.Text = suptime[0]; // first value of the array
UpTime.Text = suptime[2]; // third value of the array
UpTime.Text = suptime[suptime.Length - 1]; // last value of the array
If the result of your split is:
{"A" "Z" "11:57"}
and you want your UpTime.Text to be filled with something that looks like a time value, it's kinda obvious that the value you must pick is the third one.

Is it possible to get array length inline

I have to access Dictionary<TKey, TValue> value by key (that I get from array I'm creating inline) like so:
var someString = "1.2.3";
someDictionary[someString.Split('.').ToArray()[ /---> self.Length <---/ - 1 ]];
Question: Is it possible to get array Length inline without creating new variable and assigning array to it?
You cannot do this. You need to store intermediate value in a variable if you want to access it twice.
I see no sense in trying to do this without additional variable - at least, your approach is absolutely unreadable.
However, as I understand, by [self.Length - 1] you want to access the last value in this array.
If yes, then you can just use LINQ .Last:
var someString = "1.2.3";
someDictionary[someString.Split('.').Last()]; // someDictionary["3"]

C# Refine class property which is a List<string>

I have a class property:-
public List<string> szTypeOfFileList{get;set;}
As the name suggest, the property stores user selection of types of Files of interest (.txt, .doc, .rtf, .pdf, etc).
I am trying to assess whether there is way I could refine this List as it is being populated by user entries OR, if I should wait for all entries and then call a separate method to refine the property.
What I mean by this is, let's say a particular user input is ".doc/.docx". Currently, this would be stored in the List as a single string item. However I want it to be stored as two items separately. This will keep the code in one place and wont effect future modules and such.
private List<string> _szTypeOfFileList = new List<string>();
public List<string> szTypeOfFileList
{
get
{
return _szTypeOfFileList;
}
set
{
// Some kind of validation/refining method here ?? //
}
}
EDIT:-
Because my FileTypeList is coming from a checkboxList, I had to use a different methodology than the answer I accepted (which pointed me in the right direction).
foreach (object itemchecked in FileTypeList.CheckedItems)
{
string[] values = itemchecked.ToString().Split('/');
foreach(var item in values)
TransactionBO.Instance.szTypeOfFileList.Add(item);
}
This part of my code is in the UI class before it is passed on to the Business class.
If you know that it'll always be split with a "/" character, just use a split on the string. Including a simple bit of verification to prevent obvious duplicates, you might do something along the lines of:
string[] values = x.Split('/');
foreach (string val in values) {
if (!_szTypeOfFileList.Contains(val.ToLower().Trim())) {
_szTypeOfFileList.Add(val.ToLower().Trim());
}
}
You can also use an array of characters in place of the '/' to split against, if you need to consider multiple characters in that spot.
I would consider changing the List to something more generic. Do they really need a List ...or maybe a collection? array? enumerable ? (have a read through this link )
second, in your Set method, you'll want to take their input, break it up and add it. Here comes the question: is a list the best way of doing it ?
What about duplicate data ? do you just add it again? do you need to search for it in order to figure out if you're going to add it ?
Think about dictionary or hashtable, or any of type of collection that will help you out with your data . I would have a read through : this question (oh my ... wrong link ... nobody complained though ... so much for providing links ... :)
var extensions = userInput.Split('/').ToList();

How to make arrays values equal in C#?

Let's say that I have 2 string arrays with different values:
string[] sArray1 = new string[3]{"a","b","c"};
string[] sArray2 = new string[3]{"e","f","g"}
And I want to make values of sArray1 equal to values of sArray2 (I know I can write it like this) : sArray1[0] = sArray2[0]; sArray1[1]= sArray2[1]; sArray1[2]=sArray2[2];
For 3 values it's easy, but what if I had 100 values in an array? Is there any other way that I can make array values equal?
p.s. sorry for my bad English :(
Something like this (with a little error checking):
if (sArray2.Length == sArray1.Length)
{
sArray2.CopyTo(sArray1, 0);
}
Regards
I'm assuming you want to keep the reference to the original array in sArray1? Then do this:-
Array.Copy(sArray2, sArray1, sArray1.Length);
If you want them to function independently of each other than you can use .Clone() as of .NET 5.0
string[] sArray1 = (string[])sArray2.Clone();
In the above scenario if you change a value in one array it will not affect the other - this is called a "shallow copy" (AKA copy by val). If you want the values in both arrays to be tied to each other (typically not desirable) you can do a simple assignment like this:
string[] sArray1 = sArray2;
In this case if you change a value in either array the value(s) in the other array will update (AKA copy by ref).

NULLs in string array

How to remove Null values in string array
Like { ,-2,3, ,-4,+5, ,66...}
I need to remove those null values in between and re-size the array
I don't want to use lists
I don't want to create a new array
Please let me know if it is possible with simple code.
Thank You.
No, it's not possible without creating a new array. You can't resize an array.
You can easily create a new array without empty strings and null references like this:
string[] items = new string[] { "", "-2", "3", null, "-4", "+5", null, "66" };
items = items.Where(s => !String.IsNullOrEmpty(s)).ToArray();
If you don't want to create a new array, then no, it's not possible. You cannot add or remove an item from a simple array (as in, string[]).
The most straightforward way to accomplish what you want to achieve (if you remove your second requirement) would be:
Count the number of null values in your source array
Create a new array of the same length as your source array minus the number of nulls from step 1
Copy all non-null values from your source array into the new array
(Optional) Set the reference to your source array (e.g., srcArray) to your new array
As Dan said, you can't add or remove values from an Array. You can, however, use LINQ to remove the values and produce a second array.
originalArray = originalArray.Where(s => !string.IsNullOrEmpty(s)).ToArray()
Probably not the most performant solution but...
array.Where(s => s != null).ToArray();
It will create a new array, but I cannot think of a solution that won't.
Before deciding how to proceed, you really need to think about who holds a reference to the array you are operating on.
If the array is not referenced by any other code (as a member of a class, as a captured variable in a lambda, or in some collection somewhere) then you shouldn't worry about creating a new array. In that case I would use something like what #Codesleuth or #Guffa suggest.
However, if other code may exist that holds a reference to this same array - then you are out of luck, unless you can safely identify and update the references held in those other places. This is a hard thing to do - and you should be very careful assuming that you can always update all other places where a reference is held.
Am I the only one here that would scan the array and move the members back over the NULLs, therefore making a continuous list of non-nulls.
This doesn't create a new array and it's simple to implement and it's immportant to know you can move the entries around the array.
Unfortunately I'm at work so can not supply full code, however you would implement it by searching the array for NULLs then moving the remaining items in the array up one. Keep doing this until the end. I would suggest clearing the remaining entires once the search is completed.
string[] _array= new string[] { "", "z", "d", null, "a", "b", null, "66" };
// select non-null elements only
_array= _array.Where(a => !String.IsNullOrEmpty(a)).ToArray();

Categories

Resources