So I have a question that ask for a Movies method, to accept a name as string and a integer(represents time in minutes). So if you call this method without an integer minutes is set to a default of 90. Then the main method shows that you can call the movies method with only a string as well show you can call it with a string and integer.
static void Main()
{
Console.WriteLine("Movie title is {0}, and time is", MovieListing("x") );
}
private static string MovieListing(string name, int defaultTime = 60)
{
string Name, stringTime;
int time;
bool isValid;
Console.Write("What is the name of the movie?");
Name = Console.ReadLine();
Console.Write("What is the time of the movie? Default is 90 if left blank");
stringTime = Console.ReadLine();
time = Convert.ToInt32(stringTime);
}
So Im left blank thinking how to get the program to tell if the user entered a time int and use that or if they are just using the default 90 and passing them back to the main method sorry if the codes a mess was trying different ways without much success
You can use the ternary operation to check if the entered value is empty:
time = string.IsNullOrEmpty(stringTime) ? defaultTime : Convert.ToInt32(stringTime);
It will parse the stringTime if filled, else it will take the default.
Here's a better way to do this, using a simple Movie object to hold the values. This should print out two hardcoded lines to demo and then ask the user for input:
private class Movie
{
private readonly int _defaultLength = 90;
public string Title { get; set; }
public int Length { get; set; }
// constructor without length - use default length
public Movie(string title)
{
this.Title = title;
this.Length = _defaultLength;
}
// constructor with both properties
public Movie(string title, int length)
{
this.Title = title;
// make sure Length is valid
if (length > 0)
this.Length =length;
else
this.Length = _defaultLength;
}
}
static void Main()
{
// make a Movie object without length
var shortMovie = new Movie("Zombieland");
// make a Movie object and specify length
var longMovie = new Movie("Lawrence of Arabia", 216);
Console.WriteLine("{0} is {1} minutes long", shortMovie.Title, shortMovie.Length);
Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length);
// get input from user: title
Console.Write("What is the name of another movie?");
var userTitle = Console.ReadLine();
// get input from user: length
Console.Write("What is the length of {0}? Default is 90 if left blank", userTitle);
var userTime = Console.ReadLine();
// try to convert user input to an int and call Movie constructor to create a new object
int userTimeConverted = 0;
Movie userMovie;
if (Int32.TryParse(userTime, out userTimeConverted))
{
// make a new Movie object with the user's input
userMovie = new Movie(userTitle, userTimeConverted);
}
else
{
// make a new Movie object without the user's input
userMovie = new Movie(userTitle);
}
Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length);
}
By building a separate Movie object, we can move most or all of the logic needed for storing a default length and checking to see if the length is valid out of the Main() method. This should hopefully be much cleaner and easier to read.
As an added bonus, we can create as many instances of Movie as we want - as demonstrated in the above code.
Set the default value to something you wouldnt expect the user to enter and detect and handle that.
private static string MovieListing(string name, int defaultTime = -1)
{
var isDefaultUsed = false;
if (defaultTime = -1)
{
isDefaultUsed = true;
defaultTime = 60;
}
string Name, stringTime;
int time;
bool isValid;
Console.Write("What is the name of the movie?");
Name = Console.ReadLine();
Console.Write("What is the time of the movie? Default is 90 if left blank");
stringTime = Console.ReadLine();
time = Convert.ToInt32(stringTime);
}
Related
I try to transition a Monopoly Banking python programming I made into C#.
I used the main module is where I declare all my global variables, however, I don't quite understand how to call a module in another module without all the required variables passed into it.
https://pastebin.com/bVdt5nrP
For example on line 50 i try running SetCustom module however i don't have all the parameters that are required passed into MainMenu, I really don't wanna pass every Parameter into every module cause that just ends in mess and confusion. Is there away i can work around this or do i have to do everything messy?
Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MonopolyCSharpNonForm
{
class Program
{
static void Main(string[] args)
{
//Primary Settings
int StartingBallance = 2000;
int PassGo = 200;
int Bail = 50;
int IncomeTax = 100;
int SuperTax = 200;
string TaxLocation = 1; // 1 goes to the bank
//Players/Economy
string Player1 = "Player1";
string Player2 = "";
string Player3 = "";
string Player4 = "";
int Ballance1 = 2000;
int Ballance2 = 2000;
int Ballance3 = 2000;
int Ballance4 = 2000;
int FreeParking = 0;
string[] BankRupties = { };
MainMenu(); // Calling Main Menu
}
static void MainMenu()
{
Console.WriteLine("Welcome to Monpoly Banker V4");
Console.WriteLine("Would you to use the Default or Custom settings?"); //Ask for Default or Custom option
string LocalOption = Console.ReadLine(); //Record the option as a local variable 'LocalOption'
while (LocalOption != "Default" && LocalOption != "Custom")//Check if LocalOption is 'Default' or 'Custom'
{
Console.WriteLine("Niether option has been specified, type 'Default' or 'Custom'"); // If not state there is an Error.
LocalOption = Console.ReadLine(); //Record the input again.
}
if (LocalOption == "Custom") // Check if local variable is equal to custom.
{
SetCustom(ref StartingBallance, ref PassGo, ref Bail, ref IncomeTax, ref SuperTax, ref TaxLocation); //If it is run the SetCustom module below with the required parameters
}
else //Anything else it runs GettingNames module with required parameters
{
GettingNames(ref Player1, ref Player2, ref Player3, ref Player4);
}
}
static void SetCustom(ref int StartingBallance, ref int PassGo, ref int Bail, ref int IncomeTax, ref int SuperTax, ref string TaxLocation)
{
Console.WriteLine("\nHow much money is everyone starting with? "); // Ask for Starting Ballance
StartingBallance = Convert.ToInt32(Console.ReadLine()); // Change the StartingBallance to entered integer
Console.WriteLine("\nHow much money if you pass go? "); // Ask how much you get for passing go
PassGo = Convert.ToInt32(Console.ReadLine()); // change PassGo to entered integer
Console.WriteLine("\nHow much will bail cost? "); // Ash how much Bail is going to cost
Bail = Convert.ToInt32(Console.ReadLine()); // change Bail to entered integer
Console.WriteLine("\nHow much will income tax cost? "); // Ask how much Income Tax will cost
IncomeTax = Convert.ToInt32(Console.ReadLine()); // Change IncomeTax to entered Integer
Console.WriteLine("\nHow much will super tax cost? "); // Ask how much Super Tax will cost
SuperTax = Convert.ToInt32(Console.ReadLine()); // Record the entered integer
Console.WriteLine("\nDoes tax go to the bank for free parking? (1 = Bank | 2 = Free Parking)"); // Ask for where free parking will go (1/2 to make options easier)
TaxLocation = Console.ReadLine(); // Change TaxLocation to entered String
while (TaxLocation != "1" && TaxLocation != "2") // Check TaxLocation is either '1' or '2'
{
Console.WriteLine("Invalid Input. Try again."); // If not state its invalid input
TaxLocation = Console.ReadLine(); // Record entered Integer
}
GettingNames(ref Player1, ref Player2, ref Player3, ref Player4); // When done continue on to module Getting Names passing required parameters
}
static void GettingNames(ref string Player1, ref string Player2, ref string Player3, ref string Player4)
{
Console.WriteLine("\nWhat is Player1 name? "); // Ask Player1 name
Player1 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("\nWhat is Player2 name? "); // Ask Player2 name
Player2 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("\nWhat is Player3 name? "); // Ask Player3 name
Player3 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("\nWhat is Player4 name? "); // Ask Player4 name
Player4 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("All 4 player names have been entered."); // State all names entered and received
}
}
}
Personally, I think I would try breaking it down into individual classes first. For example, you could create a class called Game that had the settings for the game. The settings could be set through the constructor as default settings, and you can provide a custom constructor for setting individual things. Something like the following:
public class Game
{
public int PassGo;
public int Bail;
public ClassName()
{
PassGo = 200;
Bail = 50;
}
public ClassName(int customPassGo, int customBail)
{
PassGo = customPassGo;
Bail = customBail;
}
}
You could also set defaults for those parameters if you wanted by doing something like:
public ClassName(int customPassGo = 200, int customBail = 50)
{
PassGo = customPassGo;
Bail = customBail;
}
You can create objects out of the Players as well. Using objects can greatly simplify what you're trying to do here. Hope this helps!
This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 7 years ago.
Apologies on the duplicate question, I viewed similar Qs and just got confused. I have a method that is prompting a user to enter 5 different attribute values and would like to return the values chosen to be used for later decisions in the program.
while (true)
{
Console.Write("Please enter a value between 0-10 for ingenuity: ");
inputIngenuity = Console.ReadLine();
if (!UInt32.TryParse(inputIngenuity, out validIngenuity))
{
Console.WriteLine();
Console.WriteLine("Input was not a valid value for ingenuity.");
}
else if (validIngenuity < 0 || validIngenuity > 10)
{
Console.WriteLine();
Console.WriteLine("Input was not a valid value for ingenuity.");
}
else if (validIngenuity > (attributePoints - validStrength - validIntelligence - validPersonality - validSpeed))
{
Console.WriteLine();
Console.WriteLine("You do not have enough attribute points remaining.");
}
else break;
}
Console.WriteLine();
Console.WriteLine("You have " + (attributePoints - validStrength - validSpeed - validPersonality - validIntelligence - validIngenuity) + " attribute points remaining");
Console.WriteLine();
Console.WriteLine(String.Format("Strength Value = {0}", validStrength));
Console.WriteLine(String.Format("Speed Value = {0}", validSpeed));
Console.WriteLine(String.Format("Intelligence Value = {0}", validIntelligence));
Console.WriteLine(String.Format("Personaility Value = {0}", validPersonality));
Console.WriteLine(String.Format("Ingenuity Value = {0}", validIngenuity));
Console.WriteLine();
Console.WriteLine("These are your attributes!");
while (true)
{
Console.Write("Do you accept these? Type 1 for Yes, Type 2 for No. If No then choose again: ");
areYouHappyWithChoices = Console.ReadLine();
if (!UInt32.TryParse(areYouHappyWithChoices, out validChoices))
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
else if (validChoices > 2 || validChoices < 1)
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
else if (areYouHappyWithChoices == "2")
chooseAttributePoints(); //this method contains the whole routine
else
Console.WriteLine("We may now begin the game!");
break;
}
UInt32[] attributePointArray = new UInt32[5] { validStrength, validSpeed, validIntelligence, validPersonality, validIngenuity };
return attributePointArray;
The while statement for ingenuity is repeated in the method for the other 4 attributes and works without issues. I'm envisioning later code that would have different results based on how strong the user is for example. Am I going in the right direction by trying to put the values into an array? Thank you.
That would be one way to do it, however I think you'd be better off having a class or struct created to represent the data. This way you'll keep the "strong typey ness" and context of what your data is, rather than simply an array index.
example:
public class Person
{
public int Strength { get; private set; }
public int Speed { get; private set; }
public int Intel { get; private set; }
public int Personality { get; private set; }
public int Ingenuity { get; private set; }
public Person (int strength, int speed, int intel, int personality, int ingenuity)
{
this.Strength = strength;
this.Speed = speed;
this.Intel = intel;
this.Personality = personality;
this.Ingenuity = ingenuity;
}
}
Then your assignment to array:
UInt32[] attributePointArray = new UInt32[5] { validStrength, validSpeed, validIntelligence, validPersonality, validIngenuity };
return attributePointArray;
Gets updated to:
return new Person(validStrength, validSpeed, validIntelligence, validPersonality, validIngenuity);
and your return type needs to be changed from uint[] to Person
This way, rather than having to remember that returnedArray[1] is Speed (or whatever) - you would simply use returnedPerson.Speed.
You should create an object type that wraps the attributes you want to return. The return type of your method will be your newly-created object type.
Ai'm new here and new in programming as well. I'm sorry if this question is really childish but i'm having some trouble using return type in a simple c# program.
Here is my code file, at d == 2 in AccountTest class, I want the withdrawal process to start over again but this time not asking the user to enter the account balance. A friend advice to use while loop but I have no idea how to use while loop over here. Thanks in advance. :)
using System;
public class Account
{
public static void Main(string[] args)
{
Console.Write("Enter your account balance: ");
int AccountBalance = Convert.ToInt32(Console.ReadLine());
Account.Debit(AccountBalance);
}
public static void Debit(int AccountBalance)
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
int WithdrawalAmount = Convert.ToInt32(Console.ReadLine());
AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
}
}
And my Account class
public class AccountTest
{
public static int DebitTest(int AccountBalance, int WithdrawalAmount)
{
if (WithdrawalAmount > AccountBalance)
{
Console.WriteLine("\n\nDebit amount exceeded account balance.");
Console.ReadLine();
return 0;
}
else if (WithdrawalAmount <= 0)
{
Console.WriteLine("\n\nError. Incorrect amount.");
Console.ReadLine();
return 0;
}
else
{
int newBalance = AccountBalance - WithdrawalAmount;
Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
int InputNumber = Convert.ToInt32(Console.ReadLine());
if (InputNumber == 1)
{
Console.ReadLine();
return 0;
}
else if (InputNumber == 2)
{
return WithdrawalAmount;
}
else if (InputNumber == 3)
{
Console.WriteLine("\n\nYour remaining account balance is: {0}", newBalance);
Console.ReadLine();
return 0;
}
}
return 0;
}
}
Really the code should be refactored. Treating an Account like a thing makes more sense, in that it should be it's own object, and you should tell it what to do:
public class Account
{
public int Balance { get; set; }
public Account(int startBalance)
{
Balance = startBalance;
}
public void Debit(int amount) { Balance -= amount; }
public void Credit(int amount) { Balance += amount; }
}
Now, you can ask the user what they want to do with their Account, and you have room to add multiple accounts. So the program may look like:
int startingAmount = int.Parse(Console.ReadLine());
var account = new Account(startingAmount);
Console.WriteLine("1 to credit, 2 to debit, 0 to exit");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
//manipulate account
}
I'd start by reading up about static vs instance objects
first of, welcome to the coding community there is no childish question feel free to ask when ever you need, there some who will answer you with "google has the answer" but no worries a lot of other will help you, i saw you already selected an answer but ill add my point of view for you and the rest of new programmers.
a. if your new to codding never start with code it will only complicate things, instead start with a flow chart that illustrates what you to achieve from the program and from each component ( classes,functions etc. ) after you got that, its a lot easier to transform it to code, you can try using this site
it seems to be very user friendly and will draw you flow charts with the correct format.
b. like people here said before me never use variable like a,b,c because the next day youll try to continue where you left off and you will forget what you meant.
c. try to think of ways to use code to prevent repeating yourself.
d. using hard coded values is bad practice (hard coded means this:
return "this value to return is hard coded and will never change";
)
by the time i got to answer your question i already saw #Jonesy answer which is right and like what
i wanted to suggest so ill leave you with his answer.
hope this helps someone :)
The loop can be implemented in the Debit method:
public static void Debit(int AccountBalance)
{
int result = 0;
do
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
var WithdrawalAmount = Convert.ToInt32(Console.ReadLine());
result = AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
} while (result != 0);
}
You should read up on while loops. Basically what you'd want is the method to return a number that decides what the program is supposed to do next, or when it should end. Think of the loop as your engine that states "As long as [chosen key] is not pressed, keep doing something".
A small example, with [chosen key] being 1, would be:
int choice = 0;
int balance = 100;
while (choice != 1) {
Console.WriteLine("Enter withdraw amount");
string userInput = Console.ReadLine();
// This will crash the program if the user enters text.
// Used for demonstration only. int.TryParse is preferred.
int value = int.Parse(userInput);
choice = AccountTest.DebitTest(balance, value);
}
class AccountTest {
public static int DebitTest(int AccountBalance, int WithdrawalAmount)
{
// do the test if the debit is OK
//..........
// At the end, you can do this. This till return the value entered and
// choice will be given a new value. If it was 1, the program will end.
// NOTE: It's not safe to use convert as
// it will crash the program if the user enters text.
return Convert.ToInt32(Console.ReadLine());
}
}
Note that this is not a functional ATM-program, as the balance never gets updated. I leave that for you to solve since I'm guessing this is for a class in programming =)
Well, this is my version of your program. I changed the behavior a bit (like asking again when the value is invalid). It's not perfect; for example, the messages and the RequestDebit method should be handled outside the Account class, perhaps in an AccountHandler class, but all this might be overkill for this simple exercise. Anyway I hope you find it useful:
public class Account
{
public int Balance { get; set; }
public Account(int startingBalance)
{
this.Balance = startingBalance;
}
private bool Debit(int amount)
{
if (amount <= 0)
{
Console.WriteLine("\n\nError. Incorrect amount.");
return false;
}
if (amount > this.Balance)
{
Console.WriteLine("\n\nDebit amount exceeded account balance.");
return false;
}
this.Balance -= amount;
Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.");
return true;
}
public void RequestDebit()
{
bool success;
do
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
int withdrawalAmount = Convert.ToInt32(Console.ReadLine());
success = this.Debit(withdrawalAmount);
} while (!success);
}
}
class Program
{
static void Main(string[] args)
{
int accountBalance;
do
{
Console.Write("Enter your account balance: ");
accountBalance = Convert.ToInt32(Console.ReadLine());
} while (accountBalance <= 0);
var myAccount = new Account(accountBalance);
myAccount.RequestDebit();
int inputNumber;
do
{
Console.WriteLine("\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
inputNumber = Convert.ToInt32(Console.ReadLine());
switch (inputNumber)
{
case 2: myAccount.RequestDebit();
break;
case 3:
Console.WriteLine("\n\nYour remaining account balance is: {0}", myAccount.Balance);
break;
}
} while (inputNumber != 1);
}
}
public class TEST
{
static void Main(string[] args)
{
string Name = "";
double Value = 0;
Array test1 = new Array(Name, Value);
for (int i = 0; i < 2; i++)
{
Console.WriteLine("Enter A Customer:");
Name = Console.ReadLine();
Console.WriteLine("Enter {0} Insurance Value (numbers only):", Name);
Value = Convert.ToDouble(Console.ReadLine());
}
test1.Display();
Console.ReadLine();
}
}
So in another class, I have my arrays. The way it is set up, it adds one user at a time to the arrays and adds that users corresponding number in another array.
The part I am having problems with is the main coding. I prompt the user for input and want it to call my other class method and fill the array up one user at a time. BUT, I am stuck.
I know why the code above isn't working, because the object call is only called once and so the initial value is the one that is saved. But when I put the new Array(Name, Value); in the for loop it tells me that test1.Display(); is an unassigned variable.
Is there a way I can solve this. I know there is probably another easier way using list or something, but I haven't gotten that far yet. If you could explain or hint or anything, I'd appreciate it. :)
It is better in this situation to use List<T>.
You have to create a class and after that you can create a List<T> to save items:
public class Customer
{
public string Name {get;set;}
public double Value {get;set;}
}
and :
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>;
for (int i = 0; i < 2; i++)
{
Console.WriteLine("Enter A Customer:");
Customer customer = new Customer(); // create new object
customer.Name = Console.ReadLine(); // set name Property
Console.WriteLine("Enter {0} Insurance Value (numbers only):", Name);
customer.Value = Convert.ToDouble(Console.ReadLine());// set Value Property
customers.Add(customer); // add customer to List
}
Console.ReadLine();
}
I have a little problem which I have no clue how to solve. I will give the who;e code from the class so you can see what its doing:
{
class CompetitorDataFile
{
//collection of DataFileRecords - people
public List<DataFileRecord> DataFileRecords;
public string FileName = "";
//called when DataFile created
public CompetitorDataFile(string FileName)
{
//creates the collection
DataFileRecords = new List<DataFileRecord>();
this.FileName = FileName;
}
//fill DataFileRecords with stuff from text file
public void ReadDataFile()
{
foreach (string s in File.ReadAllLines(FileName))
{
if (s == "") continue;
DataFileRecord dfr = new DataFileRecord();
dfr.Name = s.Split(',')[0];
dfr.CPSA = s.Split(',')[1];
dfr.PostCode = s.Split(',')[2];
dfr.Rank = s.Split(',')[3];
dfr.Score1 = s.Split(',')[4]; //new for score system
dfr.Score2 = s.Split(',')[5]; //new for score system
dfr.Score3 = s.Split(',')[6]; //new for score system
dfr.Score4 = s.Split(',')[7]; //new for score system
dfr.Score5 = s.Split(',')[8]; //new for score system
dfr.Score6 = s.Split(',')[9]; //new for score system
dfr.Score7 = s.Split(',')[10]; //new for score system
dfr.Score8 = s.Split(',')[11]; //new for score system
dfr.TotalSingleScore = s.Split(',')[12]; //new for score system
DataFileRecords.Add(dfr);
}
}
public int FindByCPSA(string CPSA)
{
//set index to 0
int index = 0;
//go through each record looking for CPSA number match
foreach (DataFileRecord dfr in DataFileRecords)
{
if (dfr.CPSA.ToLower() == CPSA.ToLower())
{
//if it's found return the current index
return index;
}
//increase index and move to next record
index++;
}
//not found returning -1
return -1;
}
//save DataFile records to text file
public void SaveDataFile()
{
//delete backup file if found
if (File.Exists(FileName+".bck"))
File.Delete(FileName+".bck");
//make backup of existing
if (File.Exists(FileName))
File.Move(FileName, FileName + ".bck");
//create a temporary array of string
List<string> stringy = new List<string>(DataFileRecords.Count);
//go through each DataFile record and create a single string line
foreach (DataFileRecord dfr in DataFileRecords)
stringy.Add(dfr.SingleString);
//saves all strings to file
File.WriteAllLines(FileName, stringy.ToArray());
}
}
//a single record - one person
public class DataFileRecord
{
public string Name;
public string CPSA;
public string PostCode;
public string Rank;
public string Score1; //new for score system
public string Score2; //new for score system
public string Score3; //new for score system
public string Score4; //new for score system
public string Score5; //new for score system
public string Score6; //new for score system
public string Score7; //new for score system
public string Score8; //new for score system
public Int64 TotalSingleScore; // used to get total score for one user
public string SingleString
{
get
{
return string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8); //,{4} and , Score are new for score system
}
}
public string PoshSingleString
{
get
{
return string.Format("{0,-20}|{1,-10}|{2,-9}|{3,-9}|{4,2}|{5,2}|{6,2}|{7,2}|{8,2}|{9,2}|{10,2}|{11,2}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8);
//return SingleString.Replace(",0", ""); //may be used to replace 0
//return SingleString.Replace(",", ", ");
}
I have a problem with this line of code
dfr.TotalSingleScore = s.Split(',')[12];
TotalSingleScore is the only int (all others are strings) as a result I get this error:
"Error 1 Cannot implicitly convert type 'string' to 'long'"
How do I go about solving this? Code is C# and software is VS 2008 Pro
Thanks
use long.Parse or long.TryParse.
Since TotalSingleScore is declared as Int64, you have to use Int64.Parse.
Sample: dfr.TotalSingleScore = Int64.Parse(s.Split(',')[12]);
dfr.TotalSingleScore = Int64.Parse(s.Split(',')[12]);
Int64.TryParse()
Take your string and convert it. Like others stated the TryParse or Parse methods work great if the data might not be the casting type. But you can also do it this way using System.Convert.
dfr.TotalSingleScore = Convert.ToInt64(s.Split(',')[12]);
http://msdn.microsoft.com/en-us/library/system.convert.toint64.aspx
Just curious, why are you splitting the string everytime? Wouldn't it be better if you just split it once and reuse the array?
var myArray = s.split(',');
dfr.Name = myArray[0];
dfr.CPSA = myArray[1];
dfr.PostCode = myArray[2];
dfr.Rank = myArray[3];
dfr.Score1 = myArray[4]; //new for score system
dfr.Score2 = myArray[5]; //new for score system
dfr.Score3 = myArray[6]; //new for score system
dfr.Score4 = myArray[7]; //new for score system
dfr.Score5 = myArray[8]; //new for score system
dfr.Score6 = myArray[9]; //new for score system
dfr.Score7 = myArray[10]; //new for score system
dfr.Score8 = myArray[11]; //new for score system
:
etc
Not an answer for your question, but I thought I had to suggest this.